Skip to content

Troubleshooting

Huafu Gandon edited this page Sep 19, 2018 · 4 revisions

This page is for versions until 23.1.4

Troubleshooting common issues


jest.mock hoisting

cannot call mockImplementation() of ...

Modules are not mocked when I use jest.mock() in my tests

Babel Jest hoist jest.mock() calls to the top of the file, and that is done using Babel. So if you have skipBabel: true in your TS Jest options, you must move the jest.mock calls to the top of your test file, before the imports.

CommonJS compatibility

cannot call foo() of undefined

...has no property 'default'

Most likely you're missing esModuleInterop: true in the compilerOptions of your TypeScript config file

Incomplete transform in Jest options

SyntaxError: import...

SyntaxError: export...

By default the transform option of Jest config is pre-defined to use Babel for JavaScript files. When you set it for TS Jest (with '\\.tsx?$': 'ts-jest' for example), don't forget to also add one for your JS files if you have some which need to be transformed (usually '\\.jsx?$': 'babel-jest').

Missing dependencies

I've just installed ts-jest and it complains about not finding babel-jest

We use Babel Jest to hoist jest.mock calls and for coverage, so you'll most likely want to either disable it (skipBabel: true in TS Jest options) or install it (npm i --save-dev babel-jest or yarn add --dev babel-jest)

React : wrong line numbers

When using React 16 with Node version 8, you might see wrong line numbers for errors originating from tsx files. There's an issue with more details on this.

TypeScript paths (module resolution) and Jest moduleNameMapper

When using TypeScript paths (module resolution), you will need to configure in Jest configuration moduleNameMapper to let Jest knows and resolve correctly your files.

For example: In your tsconfig.json, you define something like

"paths": {
   "@core/*": ["app/core/*"],
   ...
}

Then in your Jest configuration moduleNameMapper you need to define:

"moduleNameMapper": {
   "^@core/(.*)$": "<rootDir>/src/app/core/$1",
   ...
}