Skip to main content
Version: 29.6

Solución de problemas

UH oh, ¿algo salió mal? Utilice esta guía para resolver problemas con Jest.

Los tests están fallando y no sabes por qué

Try using the debugging support built into Node. Coloque una instrucción debugger; en cualquiera de sus tests, y luego, en el directorio de su proyecto, ejecute:

node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here]
or on Windows
node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand [any other arguments here]

This will run Jest in a Node process that an external debugger can connect to. Note that the process will pause until the debugger has connected to it.

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.

The Chrome Developer Tools will be displayed, and a breakpoint will be set at the first line of the Jest CLI script (this is done to give you time to open the developer tools and to prevent Jest from executing before you have time to do so). Haga clic en el botón que se muestra como un botón de "reproducción" en el lado superior derecho de la pantalla para continuar la ejecución. Cuando Jest ejecuta el test que contiene la instrucción debugger, la ejecución se detendrá y podrá examinar el ámbito actual y la pila de llamadas.

note

The --runInBand cli option makes sure Jest runs the test in the same process rather than spawning processes for individual tests. Normalmente Jest paraleliza las ejecuciones de los tests a través de procesos, pero es difícil depurar muchos procesos al mismo tiempo.

Debuggeando en Código VS

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

Para aderir el debugger que trae por defecto, ejecute sus pruebas como se establece aquí:

node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here]
or on Windows
node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand [any other arguments here]

Luego adiera el debugger de VS Code utilizando la siguente configuración de launch.json:

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

Para iniciar y añadir automáticamente a un proceso que ejecuta sus pruebas, utilizar la siguiente instalación:

{
"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"
}
]
}

o la siguiente para 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"
}
]
}

Si está utilizando el create-react-app de Facebook, puede debugear sus pruebas de Jest con la siguente configuración:

{
"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"
}
]
}

Puede encontrar más información sobre depuración en Node aquí.

Debuggeando con WebStorm

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

Problemas de caché

The transform script was changed or Babel was updated and the changes aren't being recognized by Jest?

Reintente con --no-cache. Jest mantiene cache de archivos de módulo transformado para acelerar la ejecución de la prueba. If you are using your own custom transformer, consider adding a getCacheKey function to it: getCacheKey in Relay.

Promesas no resueltas

Si una promesa no es resuelta totalmente, podría producirse el siguiente error:

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

Comúnmente eso está siendo causado por conflictos en las implementaciones promesa. 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

Problemas con Watchman

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

Also see watchman troubleshooting.

Los tests son extremadamente lentos en Docker y/o en el servidor de integración continua (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.

Para este fin, puede ejecutar pruebas en el mismo hilo usando --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. Específicamente en Travis-CI, esto puede reducir el tiempo de ejecución de prueba a la mitad. Nota: El plan gratis de Travis CI disponible para proyectos de código abierto sólo incluye 2 núcleos CPU.

# 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 wraps Istanbul, and therefore also tells Istanbul what files to instrument with coverage collection. 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.

Defining Tests

Tests must be defined synchronously for Jest to be able to collect your tests.

As an example to show why this is the case, imagine we wrote a test like so:

// 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.

¿Aún sin resolver?

Ver Ayuda.