Troubleshooting
Упс, что-то пошло не так? Используйте данное руководство для решения проблем с Jest.
Тесты проваливаются и вы не знаете почему #
Попробуйте использовать поддержку отладки, встроенную в Node.
Note: Debugging support with Jest only supports
node debug
; it does yet supportnode inspect
due to an upstream issue in nodejs/node#7583. Until the upstream issue is resolved, debugging with Node is not available when using Node v8.x. For more details, see facebook/jest#1652.
Поместите инструкцию debugger;
в любом из ваших тестов, а затем, в каталоге вашего проекта, запустите:
node --debug-brk ./node_modules/.bin/jest --runInBand [any other arguments here] or on Windows node --debug-brk ./node_modules/jest/bin/jest.js --runInBand [any other arguments here]
Это запустит Jest в процессе Node к которому может подключиться внешний отладчик. Обратите внимание, что процесс приостановится до тех пор пока к нему подключен отладчик.
Например для подключения отладчика Node inspector к приостановленному процессу, вам сначала потребуется его установить (если вы этого еще не сделали):
npm install --global node-inspector
Затем просто запустите его:
node-inspector
This will output a link that you can open in Chrome. After opening that link, 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 simply to give you time to open the developer tools and to prevent Jest from executing before you have time to do so). Click the button that looks like a "play" button in the upper right hand side of the screen to continue execution. When Jest executes the test that contains the debugger
statement, execution will pause and you can examine the current scope and call stack.
Note: the
--runInBand
cli option makes sure Jest runs test in the same process rather than spawning processes for individual tests. Normally Jest parallelizes test runs across processes but it is hard to debug many processes at the same time.
Более подробную информацию об отладке Node можно найти здесь.
Проблемы кеширования #
The transform script was changed or babel was updated and the changes aren't being recognized by Jest?
Retry with --no-cache
. Jest caches transformed module files to speed up test execution. If you are using your own custom transformer, consider adding a getCacheKey
function to it: getCacheKey in Relay.
Unresolved Promises #
If a promise doesn't resolve at all, this error might be thrown:
- Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.`
Most commonly this is being caused by conflicting Promise implementations. Consider replacing the global promise implementation with your own, for example global.Promise = require.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(10000); // 10 second timeout
Проблемы с Watchman #
Try running Jest with --no-watchman
or set the watchman
configuration option to false
.
Also see watchman troubleshooting.
Тесты очень медленные при использовании Docker и/или сервера непрерывной интеграции. #
Хотя большую часть времени, на современных компьютерах с быстрыми твердотельными дисками, Jest исполняется очень быстро, при некоторых конфигурациях Jest может исполнятся медленно как заметили наши пользователи.
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 npm test (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. 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.
# Using Jest CLI jest --maxWorkers=4 # Using npm test (e.g. with create-react-app) npm test -- --maxWorkers=4
Tests are slow when leveraging automocking #
Whether via automock: true
in config or lots of jest.mock('my-module')
calls in tests, automocking has a performance cost that can add up in large projects. The more dependencies a module has, the more work Jest has to do to mock it. Something that can offset this performance cost significantly is adding a code transformer that moves import
or require
calls from the top of a module, where they are always executed, down into the body of the module, where they are usually not executed. This can lower the number of modules Jest has to load when running your tests by a considerable amount.
To transform import
statements, there is babel-plugin-transform-inline-imports-commonjs, and to transform require
statements, there is Facebook's inline-requires
babel plugin, which is part of the babel-preset-fbjs
package.
I'm using npm3 and my node_modules aren't properly loading. #
Upgrade jest-cli
to 0.9.0
or above.
I'm using babel and my unmocked imports aren't working? #
Upgrade jest-cli
to 0.9.0
or above.
Explanation:
jest.dontMock('foo'); import foo from './foo';
In ES6, import statements get hoisted before all other
const foo = require('foo'); 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
:
jest.unmock('./foo'); // Use unmock! import foo from './foo'; // foo is not mocked!
See the Getting Started 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 4. We recommend that you upgrade to the latest stable release of Node. The minimum supported version is v4.0.0
. Versions 0.x.x
are not supported.
Ничего не помогло? #
Смотрите раздел помощь.