Home > OS >  jest.mock throws ReferenceError: require is not defined
jest.mock throws ReferenceError: require is not defined

Time:12-21

I am trying to learn jest framework for unit testing with nodejs v18.12.1 and specifically mocking the functions and modules. I am using jest.mock() method to mock a module but I get this error while running the tests:ReferenceError: require is not defined in the line where jest.mock() is being called.

This is the code that has to be tested:

export function add(a, b) {
  return a   b;
}


export function subtract(a, b) {
  return a - b;
}

This is my test code:

import * as mathcode from '../mathcode';
import {jest, describe, test, expect} from '@jest/globals';

jest.mock('../mathcode');

describe('mathcode', () => {
  test('adds numbers', () => {
    expect(mathcode.add(1,2)).toBeUndefined();
  })
})

This is my jest config:

{
  "transform":{"\\.[jt]sx?$": "babel-jest"},
  "verbose":true,
  "automock": false,
  "modulePathIgnorePatterns":["<rootDir>/node_modules/"],
  "roots": ["<rootDir>/__tests__/"]
}

This is my package.json:

{
  "name": "sample",
  "version": "1.0.0",
  "description": "sample package to learn jest",
  "main": "index.js",
  "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
    "start": "node index.js"
  },
  "author": "rakesh",
  "license": "ISC",
  "devDependencies": {
    "@babel/preset-env": "^7.20.2",
    "jest": "^29.3.1"
  },
  "type": "module"
}

This is the babel.config.json:

{
  "presets": [["@babel/preset-env", {"targets": {"node": "current"}}]]
}

Can someone help me fix this issue?

CodePudding user response:

To fix this error, you should remove the --experimental-vm-modules flag from the jest command in your package.json scripts. This will allow Jest to use the built-in require function when running your tests.

Your package.json scripts should look like this:

"scripts": {
  "test": "jest",
  "start": "node index.js"
}

You may also need to update your jest configuration to enable the use of ESM. You can do this by adding the following field to your jest config:

"moduleFileExtensions": ["js", "mjs", "jsx", "ts", "tsx"],

This will tell Jest to treat files with the .mjs extension (which is used for ESM) as module files.

  • Related