我想知道是否有更好的方法来禁用特定 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
似乎只适用于它。
最佳答案
对于特定的规范文件,Andreas 的已经足够好了。下面的设置将抑制所有测试套件的 console.log
语句,
jest --silent
(或)
要自定义警告、信息和调试
,您可以使用以下设置
tests/setup.js 或 jest-preload.js 在setupFilesAfterEnv 中配置
global.console = {
...console,
// uncomment to ignore a specific log level
log: jest.fn(),
debug: jest.fn(),
info: jest.fn(),
// warn: jest.fn(),
// error: jest.fn(),
};
jest.config.js
module.exports = {
verbose: true,
setupFilesAfterEnv: ["<rootDir>/__tests__/setup.js"],
};
关于javascript - 在单元测试中禁用控制台的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44467657/