【发布时间】: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