我尝试使用 jest 来模拟导入的函数,但出现此错误 TypeError: Assignment to constant variable.
或 TypeError: Cannot assign to read only property 'sum' of object '[object Module]'
,我希望我得到我在这个测试中 mock 的返回值
尝试 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);
})
尝试 2import { 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);
})
尝试 3import { 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);
})
我正在关注 Jest 文档 https://jestjs.io/docs/ecmascript-modules设置我的配置包.json
{
"type": "module",
"scripts": {
"test": "NODE_OPTIONS=--experimental-vm-modules jest"
},
}
jest.config.jsmodule.exports = async () => {
return {
verbose: true,
transform: {}
};
};
我创建了这个 repo 用于复制 https://github.com/fei1990a/jest-esm/tree/main感谢您的任何帮助
最佳答案
这是我想出的解决方法。
import { jest } from "@jest/globals";
beforeAll(() => {
jest.unstable_mockModule("./util.js", () => ({
sum: jest.fn(() => { return 2 }),
}));
});
afterEach(() => {
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
关于javascript - 使用 JEST 和 ESM 进行快速测试给我错误 "TypeError: Cannot assign to read only property ' sum' of object '[object Module]'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72486226/