【发布时间】:2017-11-12 01:17:39
【问题描述】:
我想知道是否有更好的方法来禁用控制台错误 在 特定的 Jest 测试(即,恢复原始控制台 在每次测试之前/之后)。
这是我目前的做法:
describe("Some description", () => {
let consoleSpy;
beforeEach(() => {
if (typeof consoleSpy === "function") {
consoleSpy.mockRestore();
}
});
test("Some test that should not output errors to jest console", () => {
expect.assertions(2);
consoleSpy = jest.spyOn(console, "error").mockImplementation();
// some function that uses console error
expect(someFunction).toBe("X");
expect(consoleSpy).toHaveBeenCalled();
});
test("Test that has console available", () => {
// shows up during jest watch test, just as intended
console.error("test");
});
});
有没有更简洁的方法来完成同样的事情? 我想避免使用spyOn,但mockRestore 似乎只能使用它。
谢谢!
【问题讨论】:
-
我不小心隐藏了一个真正的错误。理想情况下,您应该尝试做的第一件事是诊断警告或错误。如果它真正是良性的,下面有很多答案可以帮助隐藏它。
-
@DevinRhode,这是一个不错的建议但是在某些情况下,控制台输出是测试的一部分,例如测试函数中的错误处理代码。有时您可能希望调用控制台记录的第 3 方代码,而不是模拟它。
标签: javascript unit-testing mocking jestjs