Express test using JEST and ESM give me error "TypeError: Cannot assign to read only property 'sum' of object '[object Module]'"

Viewed 234

i tried to using jest for mocking imported function but i got this error TypeError: Assignment to constant variable. or TypeError: Cannot assign to read only property 'sum' of object '[object Module]', i expect that i got return value that i mocked in this test

Attempt 1

import { jest } from '@jest/globals'
import * as util from "./util.js"

it("TypeError: Cannot assign to read only property 'sum' of object '[object Module]'", () => {
  jest.spyOn(util, "sum").mockImplementation(() => { return 2 })
  
  expect(sum(1, 2)).toBe(2);
})

Attempt 2

import { jest } from '@jest/globals'
import { sum } from './util.js'

it("TypeError: Cannot assign to read only property 'sum' of object '[object Module]'", () => {
  jest.mock("./util.js", () => ({
    __esModule: true,
    sum: jest.fn().mockReturnValue(2),
  }));
  
  expect(sum(1, 2)).toBe(2);
})

Attempt 3

import { jest } from '@jest/globals'
import { sum } from "./util.js"

it("TypeError: Assignment to constant variable.", () => {
  sum = jest.fn(() => { return 2 })
  expect(sum(1, 2)).toBe(2);
})

i'm following jest documentation https://jestjs.io/docs/ecmascript-modules to setup my config

package.json

{
  "type": "module",
  "scripts": {
    "test": "NODE_OPTIONS=--experimental-vm-modules jest"
  },
}

jest.config.js

module.exports = async () => {
  return {
    verbose: true,
    transform: {}
  };
};

i created this repo for reproduction https://github.com/fei1990a/jest-esm/tree/main

Thankyou for any help

1 Answers

Here is the workaround I came up with.

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

beforeAll(() => {
  jest.unstable_mockModule("./util.js", () => ({
    sum: jest.fn(() => { return 2 }),
  }));
});

afterAll(() => {
  jest.clearAllMocks();
});

test("should sum value be 2", async () => {
  const { sum } = await import("./util.js");
  expect(sum(1, 2)).toBe(2);
});

Reference : https://github.com/facebook/jest/issues/10025

Related