我想知道是否有更好的方法在特定的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似乎只与它一起工作。
奇怪的是,上面的答案(除了Raja的精彩答案,但我想分享其他失败的奇怪方式,以及如何清除mock,这样其他人就不会浪费我的时间)似乎成功地创建了mock,但没有抑制到控制台的日志记录。
Both
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
and
global console = {
warn: jest.fn().mockImplementation(() => {});
}
成功安装模拟(我可以使用expect(console.warn). tobecalledtimes(1)并且它通过),但它仍然输出警告,即使模拟实现似乎应该替换默认值(这是在jsdom环境中)。
最终,我找到了一个解决问题的黑客,并将以下内容放在配置中SetupFiles加载的文件中(注意,我发现有时是全局的。$不为我工作时,把jquery到全局上下文中,所以我只是设置我所有的全局在我的设置)。
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {});
const consoleLog = jest.spyOn(console, 'log').mockImplementation(() => {});
const consoleDebug = jest.spyOn(console, 'debug').mockImplementation(() => {});
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {});
Object.defineProperty(global, 'console', {value: {
warn: consoleWarn,
log: consoleLog,
debug: consoleDebug,
error: consoleError}});
它感觉很难看,然后我不得不把如下代码放在每个测试文件中,因为beforeEach没有在SetupFiles引用的文件中定义(也许你可以把两者都放在SetupFilesAfterEnv中,但我没有尝试过)。
beforeEach(() => {
console.warn.mockClear();
});
向@Raja的最佳答案致敬。这是我正在使用的(我会注释,但不能在注释中共享多行代码块)。
与jest v26,我得到这个错误:
We detected setupFilesAfterEnv in your package.json.
Remove it from Jest configuration, and put the initialization code in src/setupTests.js:
This file will be loaded automatically.
因此,我不得不从我的jest配置中删除setupFilesAfterEnv,并将其添加到src/setupTests.js中
// https://stackoverflow.com/questions/44467657/jest-better-way-to-disable-console-inside-unit-tests
const nativeConsoleError = global.console.error
global.console.error = (...args) => {
if (args.join('').includes('Could not parse CSS stylesheet')) {
return
}
return nativeConsoleError(...args)
}