gpt4 book ai didi

javascript - 使用 JEST 和 ESM 进行快速测试给我错误 "TypeError: Cannot assign to read only property ' sum' of object '[object Module]'"

转载 作者:行者123 更新时间:2023-12-05 00:29:43 25 4
gpt4 key购买 nike

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

尝试 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);
})
我正在关注 Jest 文档 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
感谢您的任何帮助

最佳答案

这是我想出的解决方法。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com