笑话:在单元测试中禁用控制台的更好方法 [英] Jest: Better way to disable console inside unit tests
问题描述
我想知道是否有更好的方法来禁用控制台错误 在 特定的 Jest 测试(即,恢复原始控制台 在每次测试之前/之后).
这是我目前的做法:
describe("一些描述", () => {让控制台间谍;beforeEach(() => {if (typeof consoleSpy === "function") {consoleSpy.mockRestore();}});test("一些不应该向开玩笑控制台输出错误的测试", () => {expect.assertions(2);consoleSpy = jest.spyOn(console, "error").mockImplementation();//一些使用控制台错误的函数期望(someFunction).toBe("X");期望(consoleSpy).toHaveBeenCalled();});test("有控制台可用的测试", () => {//在玩笑手表测试期间出现,正如预期的那样控制台.错误(测试");});});
有没有更简洁的方法来完成同样的事情?我想避免 spyOn
,但 mockRestore
似乎只适用于它.
谢谢!
对于特定的规范文件,Andreas 的已经足够好了.以下设置将禁止所有测试套件的 console.log
语句,
jest --silent
(或)
要自定义警告、信息和调试
,您可以使用以下设置
__tests__/setup.js 或 jest-preload.js 在 setupFilesAfterEnv
global.console = {log: jest.fn(),//console.log 在测试中被忽略//保留其他方法的本机行为,使用它们在您自己的测试中打印出来,而不是 `console.log`错误:console.error,警告:console.warn,信息:console.info,调试:console.debug,};
jest.config.js
module.exports = {详细:真实,setupTestFrameworkScriptFile: "<rootDir>/__tests__/setup.js",};
<块引用>
Jest v24.x 注意:setupTestFrameworkScriptFile 已被弃用,取而代之的是setupFilesAfterEnv.
module.exports = {详细:真实,setupFilesAfterEnv: ["<rootDir>/__tests__/setup.js"],};
I wonder if there is a better way to disable console errors inside a specific Jest test (i.e., restore the original console before/after each test).
Here is my current approach:
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");
});
});
Is there a cleaner way of accomplishing the same thing? I would like to avoid spyOn
, but mockRestore
only seems to work with it.
Thanks!
For particular spec file, Andreas's is good enough. Below setup will suppress console.log
statements for all test suites,
jest --silent
(or)
To customize warn, info and debug
you can use below setup
__tests__/setup.js or jest-preload.js configured in setupFilesAfterEnv
global.console = {
log: jest.fn(), // console.log are ignored in tests
// Keep native behaviour for other methods, use those to print out things in your own tests, not `console.log`
error: console.error,
warn: console.warn,
info: console.info,
debug: console.debug,
};
jest.config.js
module.exports = {
verbose: true,
setupTestFrameworkScriptFile: "<rootDir>/__tests__/setup.js",
};
Jest v24.x Note: setupTestFrameworkScriptFile is deprecated in favor of setupFilesAfterEnv.
module.exports = {
verbose: true,
setupFilesAfterEnv: ["<rootDir>/__tests__/setup.js"],
};
这篇关于笑话:在单元测试中禁用控制台的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!