【问题标题】:Express test using JEST and ESM give me error "TypeError: Cannot assign to read only property 'sum' of object '[object Module]'"使用 JEST 和 ESM 进行快速测试给我错误 \"TypeError: Cannot assign to read only property \'sum\' of object \'[object Module]\'\"
【发布时间】:2022-08-18 14:47:49
【问题描述】:

我尝试使用 jest 来模拟导入的函数,但我得到了这个错误 TypeError: Assignment to constant variable.TypeError: Cannot assign to read only property \'sum\' of object \'[object Module]\',我希望我得到了我在这个测试中模拟的返回值

尝试 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);
})

尝试 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);
})

尝试 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);
})

我正在关注笑话文档https://jestjs.io/docs/ecmascript-modules 来设置我的配置

包.json

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

jest.config.js

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

我创建了这个 repo 用于复制https://github.com/fei1990a/jest-esm/tree/main

感谢您的任何帮助

    标签: javascript node.js express jestjs es6-modules


    【解决方案1】:

    这是我想出的解决方法。

    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);
    });
    

    参考:https://github.com/facebook/jest/issues/10025

    【讨论】:

      猜你喜欢
      • 2016-02-22
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 2019-12-15
      相关资源
      最近更新 更多