Aller au contenu principal
Version : 29.7

Dépannage

Oh oh, quelque chose s'est mal passé ? Utilisez ce guide pour résoudre les problèmes avec Jest.

Les tests échouent et vous ne savez pourquoi

Try using the debugging support built into Node. Place a debugger; statement in any of your tests, and then, in your project's directory, run:

node --inspect-brk node_modules/.bin/jest --runInBand [tout autre argument ici]
ou sous Windows
node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand [tout autre argument ici]

Cela exécutera Jest dans un processus de Node auquel un débogueur externe peut se connecter. Notez que le processus sera mis en pause jusqu'à ce que le débogueur s'y soit connecté.

To debug in Google Chrome (or any Chromium-based browser), open your browser and go to chrome://inspect and click on "Open Dedicated DevTools for Node", which will give you a list of available node instances you can connect to. Click on the address displayed in the terminal (usually something like localhost:9229) after running the above command, and you will be able to debug Jest using Chrome's DevTools.

Les outils de développement Chrome seront affichés, et un point d'arrêt sera défini à la première ligne du script CLI de Jest (ceci est fait pour vous donner le temps d'ouvrir les outils de développement et pour empêcher Jest de s'exécuter avant que vous ayez le temps de le faire). Cliquez sur le bouton qui ressemble à un bouton « play » en haut à droite de l'écran pour continuer l'exécution. When Jest executes the test that contains the debugger statement, execution will pause and you can examine the current scope and call stack.

remarque

The --runInBand cli option makes sure Jest runs the test in the same process rather than spawning processes for individual tests. Normalement, Jest parallélise les tests à travers les processus, mais il est difficile de déboguer plusieurs processus en même temps.

Débogage dans VS Code

There are multiple ways to debug Jest tests with Visual Studio Code's built-in debugger.

Pour attacher le débogueur intégré, exécutez vos tests comme mentionné précédemment :

node --inspect-brk node_modules/.bin/jest --runInBand [tout autre argument ici]
ou sous Windows
node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand [tout autre argument ici]

Then attach VS Code's debugger using the following launch.json config:

{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Attach",
"port": 9229
}
]
}

Pour lancer et rattacher automatiquement un processus exécutant vos tests, utilisez la configuration suivante :

{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Jest Tests",
"type": "node",
"request": "launch",
"runtimeArgs": [
"--inspect-brk",
"${workspaceRoot}/node_modules/.bin/jest",
"--runInBand"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}

ou ce qui suit pour Windows :

{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Jest Tests",
"type": "node",
"request": "launch",
"runtimeArgs": [
"--inspect-brk",
"${workspaceRoot}/node_modules/jest/bin/jest.js",
"--runInBand"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}

If you are using Facebook's create-react-app, you can debug your Jest tests with the following configuration:

{
"version": "0.2.0",
"configurations": [
{
"name": "Debug CRA Tests",
"type": "node",
"request": "launch",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts",
"args": [
"test",
"--runInBand",
"--no-cache",
"--env=jsdom",
"--watchAll=false"
],
"cwd": "${workspaceRoot}",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}

More information on Node debugging can be found here.

Débogage dans WebStorm

WebStorm has built-in support for Jest. Read Testing With Jest in WebStorm to learn more.

Problèmes de Cache

Le script de transformation a été modifié ou Babel a été mis à jour et les changements ne sont pas reconnus par Jest ?

Retry with --no-cache. Jest met en cache les fichiers de modules transformés pour accélérer l'exécution des tests. If you are using your own custom transformer, consider adding a getCacheKey function to it: getCacheKey in Relay.

Promesses non résolues

Si une promesse n'est pas résolue du tout, cette erreur peut être levée :

- Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

Le plus souvent, ce problème est causé par des implémentations conflictuelles de promesses. Consider replacing the global promise implementation with your own, for example globalThis.Promise = jest.requireActual('promise'); and/or consolidate the used Promise libraries to a single one.

If your test is long running, you may want to consider to increase the timeout by calling jest.setTimeout

jest.setTimeout(10_000); // 10 second timeout

Problèmes de Watchman

Try running Jest with --no-watchman or set the watchman configuration option to false.

Also see watchman troubleshooting.

Les tests sont extrêmement lents sur le serveur Docker et/ou l'intégration continue (CI).

While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users have discovered.

Based on the findings, one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially.

In order to do this you can run tests in the same thread using --runInBand:

# Using Jest CLI
jest --runInBand

# Using your package manager's `test` script (e.g. with create-react-app)
npm test -- --runInBand

Another alternative to expediting test execution time on Continuous Integration Servers such as Travis-CI is to set the max worker pool to ~4. En particulier sur Travis-CI, cela peut réduire de moitié le temps d'exécution des tests. Note: The Travis CI free plan available for open source projects only includes 2 CPU cores.

# Using Jest CLI
jest --maxWorkers=4

# Using your package manager's `test` script (e.g. with create-react-app)
npm test -- --maxWorkers=4

If you use GitHub Actions, you can use github-actions-cpu-cores to detect number of CPUs, and pass that to Jest.

- name: Get number of CPU cores
id: cpu-cores
uses: SimenB/github-actions-cpu-cores@v2
- name: run tests
run: yarn jest --max-workers ${{ steps.cpu-cores.outputs.count }}

Another thing you can do is use the shard flag to parallelize the test run across multiple machines.

coveragePathIgnorePatterns seems to not have any effect.

Make sure you are not using the babel-plugin-istanbul plugin. Jest enveloppe Istanbul, et indique donc également à Istanbul quels fichiers doivent être traités avec la collection de couverture. When using babel-plugin-istanbul, every file that is processed by Babel will have coverage collection code, hence it is not being ignored by coveragePathIgnorePatterns.

Définition des tests

Les tests doivent être définis de manière synchronisée pour que Jest puisse collecter vos tests.

Comme exemple pour montrer pourquoi c'est le cas, imaginez que nous avons écrit un tel test :

// Don't do this it will not work
setTimeout(() => {
it('passes', () => expect(1).toBe(1));
}, 0);

When Jest runs your test to collect the tests it will not find any because we have set the definition to happen asynchronously on the next tick of the event loop. This means when you are using test.each you cannot set the table asynchronously within a beforeEach / beforeAll.

Toujours pas de solution ?

See Help.