I am using ts-jest in a vue project that contains a mixture of js and ts files. The project uses the @ character for relative mapping of imports to the directory src/renderer/. TS is throwing warnings for cannot find module. I am able to ignore the warning and run the tests by doing:
globals: {
'ts-jest': {
/* Fails on mapped import syntax without this.*/diagnostics: {
ignoreCodes: ['2307'],
},
},
},
but I would like the import to function as intended.
jest.config.js
module.exports = {
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'vue'],
transform: {
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
'.*\\.(vue)$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.tsx?$': 'ts-jest',
},
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/renderer/$1',
'^vue$': 'vue/dist/vue.common.js',
},
roots: ['<rootDir>', '<rootDir>/src/renderer'],
modulePaths: ['<rootDir>'],
setupFiles: ['<rootDir>/vue-test-setup.ts'],
snapshotSerializers: ['jest-serializer-vue'],
testMatch: ['**/test/**/*.spec.(js|jsx|ts|tsx)|**/__test__/*.(js|jsx|ts|tsx)'],
transformIgnorePatterns: ['<rootDir>/node_modules/?!(vue-timers)'],
globals: {
'ts-jest': {
/* Fails on mapped import syntax without this.*/diagnostics: {
warnOnly: true,
},
},
},
};
The test lies in test/unit/regexes.spec.ts and the import lies in src/renderer/resources/regexes.ts
The specific error I get is:
FAIL test/unit/specs/regexes.spec.ts
● Test suite failed to run
TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
test/unit/specs/regexes.spec.ts:1:19 - error TS2307: Cannot find module '@/resources/regexes'.
1 import REGEX from '@/resources/regexes';
~~~~~~~~~~~~~~~~~~~~~
It looks like you are trying to use the @ symbol to specify a relative path to the src/renderer directory in your imports, but TypeScript is unable to find the specified module.
To resolve this error, you can try the following steps:
Check that the module you are trying to import actually exists at the specified path. Make sure that there are no spelling mistakes or typos in the import statement.
Check that the path to the module is correctly specified in the moduleNameMapper section of your Jest configuration file. This will allow Jest to properly resolve the path when running the tests.
Make sure that the roots and modulePaths fields in your Jest configuration are correctly set to include the directories where your source files and tests are located. This will ensure that Jest is able to find all of the relevant files when running the tests.
If you are still experiencing issues, you may need to modify the transformIgnorePatterns field in your Jest configuration to include the path to the module that you are trying to import. This will allow Jest to correctly transform the module using the ts-jest transformer when running the tests.