Skip to content

@jest/globals breaks jest.mock #10147

@fsworld009

Description

@fsworld009

💥 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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions