'ReferenceError: jest is not defined' when running unit test
Asked Answered
D

3

68

I'm in the early stages of a new app that so far just uses vanilla JS. I'm trying to use ES6 modules for my Jest unit tests, so I followed the 2020 updated instructions on making this possible.

However, after following those instructions, I get the error ReferenceError: jest is not defined when running my unit test.

Here's my package.json:

{
  "version": "1.0.0",
  "main": "app.js",
  "type": "module",
  "jest": {
    "testEnvironment": "jest-environment-node",
    "transform": {}
  },
  "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
    "start": "node server.js"
  },
  "license": "ISC",
  "devDependencies": {
    "express": "^4.17.1",
    "jest": "^26.6.3",
    "jest-environment-node": "^26.6.2",
    "open": "^7.3.0"
  },
  "dependencies": {}
}

Below is my test file. The error occurs due to the jest.fn call:

import { getTotalNumPeople } from "./app.js";


test("Get total number of people", async () => {
    global.fetch = jest.fn(() => Promise.resolve({
            json: () => Promise.resolve({count: 15})
        })
    )
    
    expect(await getTotalNumPeople()).toBe(15);
});

Any ideas on why this is happening? I'm confident that the issue has to do with the steps I followed to support ES6 modules. Prior to these changes, my test ran fine when I simply pasted the getTotalNumPeople function in my test file.

If I comment out mocking my function, I then get a ReferenceError about fetch not being defined (since getTotalNumPeople uses fetch). So it's not just jest that's not defined.

I notice that if I do not specify jest-environment-node as my test environment, the error changes to ReferenceError: global is not defined due to referring to global.fetch in my test. Just thought I'd note that in case that helps.

Discommode answered 7/12, 2020 at 22:3 Comment(2)
Maybe I'm missing something but I was expecting your package.json to have a script like this: "test": "jest" so jest runs as a cli. More here: jestjs.io/docs/en/getting-startedGreave
@Greave I did have that script originally. But after following the instructions for enabling ES6 modules with Jest, I replaced that script with "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"Discommode
Q
91

It looks like you didn’t import jest, so you have to just add this line to the top of the file:

import {jest} from '@jest/globals'

For more details, see this issue on native support for ES6 modules in Jest.

Quarterhour answered 8/12, 2020 at 16:55 Comment(6)
This gives me a runtime error: Do not import @jest/globals` outside of the Jest test environment`Behlau
@SlavaFominII: Yup! I am getting same error! Is there any fix for the sameDarmit
this is not the full solution as getting errors for Do not import @jest/globals`Radke
Can you provide code so i can check?Quarterhour
should not import jest globallyAttorneyatlaw
what is the fix then? This was the accepted answerFarnham
C
21

while essentially the same as the answer of Rupesh - you can expose jest globally without having to import it in each test file - by adding a setup-file to the jest configuration:

"jest": {
    "setupFiles": [
        "<rootDir>/test-setup.js"
    ]
}

then add this to test-setup.js:

import { jest } from '@jest/globals';

global.jest = jest;

also in general ESM support for jest is improved by a test script in package.json as so:

"scripts": {
    "test": "node --no-warnings --experimental-vm-modules $( [ -f ./node_modules/.bin/jest ] && echo ./node_modules/.bin/jest || which jest )"
},
Continent answered 14/12, 2022 at 17:17 Comment(1)
This should be the excepted answer, instead of adding jest import to every test file. Thanks!Ellerd
V
2

I got the same error on NextJS, and I found the answer here that solved my problem:

https://github.com/FormidableLabs/jest-next-dynamic/issues/22#issuecomment-1030885706

So just remove the test from within the pages folder into a separate, e.g. __test__ folder. This is a NextJS-specific use case though.

UPDATE: Since Next introduced app folder for the new router, this is not an issue anymore, you can store the test files together with the components.

Virulence answered 8/6, 2023 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.