我有个库在我的玩笑测试中给我添麻烦了。
这个库包含在我的整个项目中,它有一个annoyingFunction,其中包含一个console.error。因此,每当我运行一个测试,我自然会得到不想要的console.error消息到处都是。
我不想模拟整个库,只想模仿annoyingFunction,所以我把它放在我的安装文件中:
jest.mock('myLibrary', () => ({
...jest.requireActual('myLibrary'),
annoyingFunction: jest.fn(),
}));这是运行的,但是,原始的annoyingFunction仍在被调用,console.error调用污染了我的测试。
如果我在控制台上记录我的模拟,我很清楚地看到了annoyingFunction: [Function: mockConstructor],所以模拟正在工作,但是出于某种原因,来自库的原始函数仍在被调用。
我在这里错过了什么?我最初的模拟设置有什么问题吗?
发布于 2022-05-10 21:03:06
可能有一些错误,但我的猜测是,annoyingFunction是在库内部调用的。请考虑下面的示例,它没有执行您可能期望的操作:
foo.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
let total = 0;
for (let i = 0; i < b; i++) {
total = add(total, a);
}
return total;
}
export {
add,
subtract,
multiply
};foo_test.js
import * as Operations from "./foo.js";
jest.mock("./foo.js", () => ({
...jest.requireActual("./foo.js"),
add: () => -999,
}));
describe("all the things", () => {
// Here, the mock does what you would expect, because you're calling the
// exported function "add."
it("can add", () => {
expect(Operations.add(1, 2)).toEqual(-999);
});
it("can subtract", () => {
expect(Operations.subtract(1, 2)).toEqual(-1);
});
// Here, the mock doesn't do what you would expect. because unbeknownst to
// you, `multiply` calls `add` _within_ the module code. The mock has no
// effect in this case.
it("can multiply", () => {
expect(Operations.multiply(1, 2)).toEqual(2);
});
});我不太确定您能对此做些什么,除了模拟库的导出方法,直到您能够控制结果。
Or...you可以为您提供问题的测试的jest.spyOn console.error,以及之后重新设置间谍。
const consoleErrorSpy = jest.spyOn(console, "error");
//...do your test...
consoleErrorSpy.mockRestore();希望这能帮上忙!
https://stackoverflow.com/questions/72192180
复制相似问题