@jest/globals breaks jest.mock
See original GitHub issueš„ Regression Report
In my project I am using babel-jest and jest 25.3.0
. I have 2 places using jest.mock
, one is in setupFiles
script (letās call it setup.js
):
jest.mock('lodash.debounce', () => func => func);
The other is on top level of one of the test files:
jest.mock('axios', () => {
const axiosMock = jest.fn();
axiosMock.CancelToken = {
source: () => ({ cancel: jest.fn() }),
};
return axiosMock;
});
This was working fine until today I added a new npm package (thus updated yarn.lock).
Initially all tests failed at setup.js with this error:
Do not import `@jest/globals` outside of the Jest test environment
After commenting out the jest.mock in setup.js, the test file with mock axios code also failed with the same error. Removing jest.mock will remove this error (but the tests will fail)
Last working version
I was using version 25.3.0
, however since this happens, the error wonāt go away even if I delete yarn.lock
, node_modules
folder and reinstall everything. I compared yarn.lock changes and noticed that @jest/globals
wasnāt there before I add new dependency today. It seems that this is introduced at 25.5.0, but since most of the jest packages reference other jest packages with versioning ^25.3.0
, @jest/globals
will still be installed even if I reinstall jest 25.3.0
.
The only workaround I can find out now is to revert jest to 24.9.0
Worked up to version: probably 24.9.0
Stopped working in version: probably all 25 and 26 versions
To Reproduce
Please refer to Regression Report
where I described what my test code looks like
Expected behavior
Test codes should run and not throw error.
Link to repl or repo (highly encouraged)
Itās a private project so canāt provide the full repo, Iāll see if I can make a minimal repo later.
Run npx envinfo --preset jest
Paste the results here:
System:
OS: Linux 4.15 Ubuntu 18.04.3 LTS (Bionic Beaver)
CPU: (2) x64 Intel(R) Core(TM) i5-5257U CPU @ 2.70GHz
Binaries:
Node: 10.18.1 - ~/.nvm/versions/node/v10.18.1/bin/node
Yarn: 1.22.0 - ~/.nvm/versions/node/v10.18.1/bin/yarn
npm: 6.13.4 - ~/.nvm/versions/node/v10.18.1/bin/npm
npmPackages:
jest: 24.9.0 => 24.9.0
Issue Analytics
- State:
- Created 3 years ago
- Reactions:18
- Comments:16
Top GitHub Comments
Spec file starting with:
results:
Problem is present while using
babel-jest
version25.5.1
. Upgradingbabel-jest
to the latest version (at the moment is26.0.1
) results to the same problem.This worked for me. So, unfortunatelly, it looks like Iām forced to use outdated
babel-jest
versionā¦ Thanks, @yubaoquan!Iām not sure weither it is a same problem. I am using ābabel-jestā: ā^26.0.1ā and āvue-jestā: ā^3.0.5ā. The jest version I found in node_modules is 24.9.0.
Every time when there is a
jest.mock
invoke in test file, the exception will throw:Below is a demo:
Workaround is use babel-jest 21.2.0