Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

486
Visualizações
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

over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda