Reputation: 2176
Using TS, exports from CJS modules can be imported with syntax as if they were named ES module exports, e.g.:
import { sync } from 'glob';
However, with Jest and ES modules, when this style of import is in a test file or in a dependency of a test file, it says SyntaxError: The requested module 'glob' does not provide an export named 'sync'
.
Going through all one by one and changing them to import glob from 'glob';
and then calling glob.sync()
seems to work, however when migrating some legacy stuff from another test runner to Jest this may not be an option, because there are a lot of those such imports in the codebase.
Reproduced here: https://github.com/themaskedavenger/tsjestcjerepro
Running jest with: node --experimental-vm-modules node_modules/jest/bin/jest.js
(as described in https://jestjs.io/docs/ecmascript-modules), and using Jest config:
resetMocks: true,
testEnvironment: "node",
testMatch: [
"**/src/**/*.(spec|test).[tj]s?(x)"
],
preset: 'ts-jest/presets/default-esm',
transform: {},
'extensionsToTreatAsEsm': [".ts", ".tsx"],
globals: {
'ts-jest': {
useESM: true,
tsconfig: {
allowSyntheticDefaultImports: true,
declaration: true,
esModuleInterop: true,
jsx: "react",
lib: ["esnext"],
module: "es2020",
moduleResolution: "node",
outDir: "build",
sourceMap: true,
strictNullChecks: true,
target: "ES2020",
}
},
}
Is there a way around this, so that import { whatever } from 'whatever'
; will work for CJS modules in jest test files?
Upvotes: 8
Views: 1845