Reputation: 2304
I have pretty straightforward question: "How to configure typescript with jest". I know that there are plenty resources for this. But no one solution worked for me.
Here is my jest.config.js
:
module.exports = {
roots: [
'<rootDir>'
],
transform: {
"^.+\\.ts$": "ts-jest"
},
testMatch: ['<rootDir>/tests/**/*.ts'],
moduleFileExtensions: ['ts', 'js'],
modulePaths: [
'<rootDir>/src/js/'
],
moduleNameMapper: {
'Services(.*)': '<rootDir>/src/js/$1'
},
};
First problem is that module name mapper does not work. I added both modulePaths
and moduleNameMapper
but no one works. It just simple says: "Can not find module ...".
Another problem is that when I fake module name mapper (for example 'i': '<rootDir>/src/js/State.ts'
and make it work, I have " Unexpected token export". But I followed this guide https://basarat.gitbooks.io/typescript/docs/testing/jest.html and I have the same code as on that example. I tried using babel for jest - the same.
Of course, I tried googling. But no success. I tried different ways - no result. I spent almost 2 hours on it. I know that there should be a simple solution for this as jest and typescript are popular packages.
Update: Here is my tsconfig.js
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es2015",
"target": "es5",
"jsx": "react",
"allowJs": true
}
}
Upvotes: 1
Views: 1165
Reputation: 74810
With the information you provided, I would guess that the problem is twofold:
moduleNameMapper
regexUnexpected token export
might indicate a wrong tsconfig.json
configuration (e.g. module
)1.) Wrap 'Services(.*)'
with regex boundaries ^$
, resulting in '^Services(.*)$'
. Otherwise it can cause weird errors, as all matching sub-strings of the module name are replaced.
Also I am not sure, if you are rather meaning '^Services/(.*)$'
(including "/")? As your dummy replacement alias changes the error type, your config seems to have an incorrect regex match, but works in other regards.
2.) Node cannot understand ES module syntax without special flags. Your error indicates, there is probably a transpile step from import/export
to CommonJS require
missing. Check your module
property in tsconfig.json
/ your test config, if it is set to "CommonJS"
. Consider the default value which depends on target
property: target === "ES3" or "ES5" ? "CommonJS" : "ES6"
.
If you use baseUrl
and paths
alias configuration in tsconfig.json
, make sure to also setup moduleNameMapper in jest config. This is a bit redundant, so ts-jest
offers a helper to extract the values from TS config. You can have a look at this example.
Hope, that gets your problem solved, otherwise a complete code example would be helpful.
Upvotes: 2