Having difficulties getting Jest to work with a TypeScript project that uses ES modules and the import
syntax. I originally wrote my project using commonjs, and the Jest tests ran fine. However, when I switched to ES Modules for learning purposes, Jest is not happy ヽ(`Д´)ノ
The tools I am working with: TypeScript, Jest, ts-jest
The issue arises with the import
syntax.
Below are the different code variations I've attempted:
// projectRoot/src/app.ts
export default someFunction = (): void => {
// some code
}
If
// projectRoot/__tests__/app.test.ts
import someFunction from '../src/app'; // without file extension
/* This runs perfectly fine */
However,
// projectRoot/__tests__/app.test.ts
import someFunction from '../src/app.ts' // with .ts
/*
● Test suite failed to run
__tests__/app.test.ts:1:25 - error TS2691: An import path cannot end with a '.ts' extension. Consider importing '../src/app' instead.
1 import information from '../src/app.ts';
*/
Additionally,
// projectRoot/__tests__/app.test.ts
import someFunction from '../src/app.js'; // with .js
/*
● Test suite failed to run
Cannot find module '../src/app.js' from '__tests__/app.test.ts'
*/
As shown in the examples above, Jest (or perhaps ts-jest?) does not like it when I import the module with an extension, which is necessary for ES Modules. I have done some research online, but it seems like the Jest documentation is not very helpful for ES Modules. The same goes for ts-jest as seen in this issue.
My project structure:
/projectRoot
├── /src/app.ts
├── /__tests__/app.test.ts
The package.json file includes
"type": "module"
tsconfig.json:
{
"compilerOptions": {
"target": "ES2015",
"module": "ESNEXT",
"outDir": "./build",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["./src"],
"exclude": ["node_modules", "**/*.test.ts"]
}
jest.config.js
export default {
"roots": [
//"<rootDir>/src"
"<rootDir>"
],
"testMatch": [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)"
],
"transform": {
"^.+\\.(ts|tsx)$": "ts-jest"
},
"preset": "ts-jest",
"testEnvironment": 'node'
}
Any help would be greatly appreciated. Thank you.