Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'ReferenceError: jest is not defined' when running unit test

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.

like image 391
Eric Avatar asked Dec 07 '20 22:12

Eric


1 Answers

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.

like image 189
Rupesh Avatar answered Sep 28 '22 06:09

Rupesh