Uh oh, something went wrong? Use this guide to resolve issues with Jest.

找不到测试失败的原因

请尝试使用 Node 内置的调试功能。

在你的单元测试中添加一条 debugger;语句,然后在项目目录中执行:

  1. node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here]
  2. or on Windows
  3. 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). 点击开发者工具中右上方调试菜单栏中的“开始调试” 按钮,让代码继续执行。 当 Jest 执行到添加了debugger; 语句的单元测试时,执行就会暂停,此时,你可以检查当前的值域和调用栈。

注︰CLI 中 —runInBand 选项能够确保 Jest 执行在同一个进程中,而非为在多个子进程中分别执行。 通常情况下,Jest 并行化测试会跨进程执行,但是很难同时调试多个进程。

Debugging in VS Code

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

To attach the built-in debugger, run your tests as aforementioned:

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

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

  1. {
  2. "version": "0.2.0",
  3. "configurations": [
  4. {
  5. "type": "node",
  6. "request": "attach",
  7. "name": "Attach",
  8. "port": 9229
  9. }
  10. ]
  11. }

To automatically launch and attach to a process running your tests, use the following configuration:

  1. {
  2. "version": "0.2.0",
  3. "configurations": [
  4. {
  5. "name": "Debug Jest Tests",
  6. "type": "node",
  7. "request": "launch",
  8. "runtimeArgs": [
  9. "--inspect-brk",
  10. "${workspaceRoot}/node_modules/.bin/jest",
  11. "--runInBand"
  12. ],
  13. "console": "integratedTerminal",
  14. "internalConsoleOptions": "neverOpen"
  15. }
  16. ]
  17. }

or the following for Windows:

  1. {
  2. "version": "0.2.0",
  3. "configurations": [
  4. {
  5. "name": "Debug Jest Tests",
  6. "type": "node",
  7. "request": "launch",
  8. "runtimeArgs": [
  9. "--inspect-brk",
  10. "${workspaceRoot}/node_modules/jest/bin/jest.js",
  11. "--runInBand"
  12. ],
  13. "console": "integratedTerminal",
  14. "internalConsoleOptions": "neverOpen"
  15. }
  16. ]
  17. }

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

  1. {
  2. "version": "0.2.0",
  3. "configurations": [
  4. {
  5. "name": "Debug CRA Tests",
  6. "type": "node",
  7. "request": "launch",
  8. "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts",
  9. "args": ["test", "--runInBand", "--no-cache", "--env=jsdom"],
  10. "cwd": "${workspaceRoot}",
  11. "protocol": "inspector",
  12. "console": "integratedTerminal",
  13. "internalConsoleOptions": "neverOpen"
  14. }
  15. ]
  16. }

更多关于 Node 调试的信息,可以查看这里

Debugging in WebStorm

The easiest way to debug Jest tests in WebStorm is using Jest run/debug configuration. It will launch tests and automatically attach debugger.

In the WebStorm menu Run select Edit Configurations…. Then click + and select Jest. Optionally specify the Jest configuration file, additional options, and environment variables. Save the configuration, put the breakpoints in the code, then click the green debug icon to start debugging.

If you are using Facebook's create-react-app, in the Jest run/debug configuration specify the path to the react-scripts package in the Jest package field and add —env=jsdom to the Jest options field.

缓存问题

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

尝试使用 —no-cache 选项。 Jest 会缓存转换的模块文件来加速测试的执行。 If you are using your own custom transformer, consider adding a getCacheKey function to it: getCacheKey in Relay.

未返回的 Promises

如果一个 Promise 并未返回任何东西(no resolve)你会看到类似于下边的报错:

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

通常这是由冲突的Promise 实现引发的。 Consider replacing the global promise implementation with your own, for example global.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

  1. jest.setTimeout(10000); // 10 second timeout

看门狗问题

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

更多详情,查看 看门狗疑难解答.

Docker 和/或 持续集成(CI,Continuous Integration)服务器中执行 Jest 测试极慢。

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

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

达成上述目的,可以使用—runInBand选项:

  1. # Using Jest CLI
  2. jest --runInBand
  3. # Using yarn test (e.g. with create-react-app)
  4. yarn 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. Specifically on Travis-CI, this can reduce test execution time in half. Note: The Travis CI free plan available for open source projects only includes 2 CPU cores.

  1. # Using Jest CLI
  2. jest --maxWorkers=4
  3. # Using yarn test (e.g. with create-react-app)
  4. yarn test --maxWorkers=4

使用 autoMock 工具时测试缓慢

无论是配置 automock: true 或者在测试中使用 jest.mock('my-module') 自动模拟会在大型项目中增加性能开销。 模块依赖越多,Jest 需要模拟的模块就越多。 有种可以大幅降低这种性能开销的方式,那就是增加一个代码转换器,将通常在模块头部执行的 importrequire 调用移动到模块内部,从而阻止他们的执行。 如此一来可以大量减少执行测试时,Jest 需要加载的模块的数量。

若要转换 import 语句,可以使用 babel-plugin-transform-inline-imports-commonjs Babel 插件,若要转换 require 语句, 可以使用 Facebook 提供的 inline-requires Babel 插件,这个插件是 babel-preset-fbjs 的一部分。

我使用了 npm 3,但 node_modules 加载失败

jest-cli 升级到 0.9.0 或者更高版本

我使用了 Babel,但未模拟的模块引入不生效?

jest-cli 升级到 0.9.0 或者更高版本

注释:

  1. jest.dontMock('foo');
  2. import foo from './foo';

在 ES6 中,模块引入出现在其他代码之前。

  1. const foo = require('foo');
  2. jest.dontMock('foo'); // Oops!

In Jest 0.9.0, a new API jest.unmock was introduced. Together with a plugin for babel, this will now work properly when using babel-jest:

  1. jest.unmock('./foo'); // Use unmock!
  2. import foo from './foo';
  3. // foo is not mocked!

See the [Getting Started]GettingStarted.md#using-babel) guide on how to enable babel support.

升级 Jest 0.9.0 测试失败?

Jest is now using Jasmine 2 by default. It should be easy to upgrade using the Jasmine upgrade guide.

If you would like to continue using Jasmine 1, set the testRunner config option to jasmine1 or pass —testRunner=jasmine1 as a command line option.

兼容问题

Jest takes advantage of new features added to Node 6. We recommend that you upgrade to the latest stable release of Node. The minimum supported version is v6.0.0. Versions 0.x.x and 4.x.x are not supported because the jsdom version used in Jest doesn't support Node 4. However, if you need to run Jest on Node 4, you can use the testEnvironment config to use a custom environment that supports Node 4, such as jest-environment-node.

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.

尚未解决问题?

这里 查看帮助