'Jest and Typescript: Cannot use import statement outside a module
Im trying to run unit tests in a monorepo where I have configured Jest and Typescript as below:
Jest:
module.exports = {
displayName: 'xplat-web-features',
preset: '../../../../jest.preset.js',
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
},
},
transform: {
'^.+\\.[tj]sx?$': 'ts-jest',
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../../../coverage/libs/xplat/web/features',
};
TSConfig:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"include": [
"**/*.spec.ts",
"**/*.spec.tsx",
"**/*.spec.js",
"**/*.spec.jsx",
"**/*.d.ts"
]
}
And when I run Jest with the nx command, I get SyntaxError: Cannot use import statement outside a module
I have tried the following with no luck
- Set babel-js as the transpiler in Jest config
- Set "module" to es6 in compilerOptions of TS config
- Run Jest with
NODE_OPTIONS=--experimental-vm-modules
Basically hitting a wall at this point and don't know where to go from here.
Solution 1:[1]
Add this to your jest config file:
"transform": {
"^.+\\.ts?$": "ts-jest"
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joe Gasewicz |
