Skip to main content
Versão: Próximo

Resolução de Problemas

Hã, algo deu errado? Use este guia para resolver problemas com Jest.

Testes estão falhando e você não sabe por que

Try using the debugging support built into Node. Coloque uma instrução debugger; em qualquer um dos seus testes e em seguida, no diretório do seu projeto, execute:

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). Clique no botão que se parece com um botão "play" no lado superior direito da tela para continuar a execução. Quando Jest executa o teste que contém a instrução debugger, a execução fará uma pausa e você pode examinar o escopo atual e a pilha de chamada.

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 execução de testes através de processos, mas é difícil de depurar vários processos ao mesmo tempo.

Depuração no VS Code

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

Para anexar o depurador embutido, execute os testes, como foi mencionado anteriormente:

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]

Em seguida, anexe depurador do VS Code usando a configuração launch.json a seguir:

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

Para iniciar automaticamente e anexar a um processo executando os seus testes, use a seguinte configuração:

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

or the following for 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"
}
]
}

Se você estiver usando o create-react-app do Facebook, você pode depurar seus testes Jesta com a seguinte configuração:

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

Mais informações sobre depuração do Node podem ser encontradas aqui.

Depuração no WebStorm

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

Problemas de Cache

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

Tente novamente com --no-cache. Jest armazena em cache os arquivos de módulo transformados para acelerar a execução de testes. If you are using your own custom transformer, consider adding a getCacheKey function to it: getCacheKey in Relay.

Promessas não resolvidas

Se uma promessa não é resolvida de forma alguma, esse erro pode ser lançado:

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

Mais comumente, isso é causado por implementações conflitantes de Promessa. 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 com Watchman

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

Também consulte solucionando problemas do watchman.

Testes são extremamente lentos no Docker e/ou servidor de Integração Contínua (CI, Continuous Integration).

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 isso, você pode executar testes na mesma "thread" 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. Especificamente no Travis-CI, isto pode reduzir o tempo de execução de teste pela metade. Nota: O plano gratuito de Travis CI disponível para projetos de código aberto inclui apenas 2 núcleos de 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 parece não ter nenhum efeito.

Certifique-se de que você não está usando o plugin de babel-plugin-Istambul. 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.

Ainda sem resolução?

Consulte a ajuda.