Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!