Reputation: 9
This is my Jest configurations:
import type { Config } from 'jest'
const config: Config = {
testEnvironment: 'node',
transform: {
'^.+\\.ts$': 'ts-jest',
'^.+\\.js$': 'babel-jest',
},
moduleFileExtensions: ['ts', 'js'],
transformIgnorePatterns: ['/node_modules/'],
extensionsToTreatAsEsm: ['.ts'],
}
export default config
And this is my typescript configuration in the tsconfig.ts:
{
"compilerOptions": {
"target": "es2021",
"module": "ESNext",
"rootDir": "./src",
"moduleResolution": "Node10",
"baseUrl": "./src",
"paths": {
"*": ["*", "src/*"]
},
"resolveJsonModule": true,
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"useUnknownInCatchVariables": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"exactOptionalPropertyTypes": true,
"noImplicitReturns": false,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts", "src/utils/excelGenerator.ts", "src/__tests__/app.test.ts"],
"files": ["src/types.d.ts"]
}
Log when I try to execute npm run test:
src/app.ts:6:50 - error TS2821: Import assertions are only supported when the '--module' option is set to 'esnext', 'nodenext', or 'preserve'.
6 import swaggerFile from '../swagger-output.json' assert { type: 'json' }; ~~~~~~~~~~~~~~~~~~~~~~~
Test Suites: 2 failed, 2 total Tests: 0 total Snapshots: 0 total Time: 3.366 s Ran all test suites.
Upvotes: 0
Views: 123
Reputation: 223259
The error describes the problem, TypeScript supports assert
only for native ESM with specific target.
For Jest with native ESM, both extensionsToTreatAsEsm
Jest option and --experimental-vm-modules
Node option have to be used, which is presumably done here. A certain TS config needs to be provided in Jest:
'^.+\\.ts$': [
'ts-jest',
{
tsconfig: {
module: 'NodeNext',
moduleResolution: 'Node16',
},
},
],
For Jest with CJS, which is more commonly occurring setup, this may require to add Babel to transforms to process compiled native ESMs further, no extensionsToTreatAsEsm
option should be used. This requires jest-chain-transform
, @babel/preset-env
and @babel/plugin-syntax-import-attributes
to be installed, with multiple Jest transforms being chained:
'^.+\\.ts$': [
'jest-chain-transform', {
transformers: [
[
'ts-jest',
{
tsconfig: {
module: 'NodeNext',
moduleResolution: 'Node16',
},
},
],
['babel-jest', {
presets: [
[
'@babel/preset-env',
{
targets: { node: 'current' }
}
]
],
plugins: [
[
'@babel/plugin-syntax-import-attributes',
{ deprecatedAssertSyntax: true }
]
]
}]
]
}
],
Notice that assert
has been deprecated in favour of with
.
Upvotes: 0