I am currently in the process of adding unit tests to a TypeScript project that utilizes compilerOptions.paths
. My goal is to mock an import for testing purposes.
However, I have encountered an issue where jest is unable to resolve the module to be mocked.
FAIL logic/index.test.ts
● Test suite failed to run
Cannot find module '@lib/foo' from 'logic/index.test.ts'
The project is using ts-jest
, which does support paths in imports. It seems like there might be an extra step needed for mocking imports.
What would be the correct approach to resolve this path-related problem?
SIMPLIFIED CASE
{
"baseUrl": ".",
"compilerOptions": {
"paths": {
"@lib/*": ["lib/*"]
}
}
}
Filesystem
* lib
* __mocks__
* foo.ts
* foo.ts
* logic
* index.ts
* index.test.ts
* tsconfig.json
* jest.config.js
// index.ts
import foo from '@lib/foo';
const logic = () => foo();
export default logic;
// index.test.ts
import 'jest';
import logic from '.';
jest.mock('@lib/foo');
// jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};