Reputation: 163
I'm having a strange issue with my unit tests and Jest that I have no idea how to solve. When I import a file in file2.ts
, the import of the same file in file1.ts
becomes undefined
. The application builds and runs, but the unit tests no longer work and throw the following error in file1.ts
:
TypeError: Cannot read property 'getModel' of undefined
This is the code:
file1.ts
import users from '../users';
const model = users.getModel();
...
file2.ts
import users from '../../users';
const model = users.getModel();
...
users.ts
export class User {
getModel() {
...
}
}
export default new User();
The unit test for file2.ts
throws the error above for file1.ts
even though I am only running the unit test for file2.ts
specifically.
If I comment out const model = users.getModel();
in file2.ts
, then the error isn't thrown.
Here are my tsconfig.json
and my jest.config.js
files:
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"pretty": true,
"sourceMap": false,
"target": "es6",
"resolveJsonModule": true,
"esModuleInterop": true,
"allowJs": true,
"outDir": "./dist",
"baseUrl": "./src"
},
"include": [
"src/**/*.ts"
],
"exclude": [
"dist",
"node_modules",
"**/*.spec.ts"
]
}
jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
collectCoverage: true,
coverageDirectory: './test-coverage'
};
Any ideas?
Upvotes: 0
Views: 2457
Reputation: 12435
You might have a circular dependency, but I can't tell from the truncated example code you posted. But circular deps can cause imports to show up as undefined due to race conditions. You can use the eslint-plugin-import/no-cycle rule to check for circular deps, and then refactor them out of your code base.
Upvotes: 0