Javascript Jest:在单元测试中禁用控制台的更好方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44467657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jest: Better way to disable console inside unit tests
提问by Apidcloud
I wonder if there is a better way to disable console errorsinsidea specific Jest test(i.e., restore the original consolebefore/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 mockRestoreonly seems to work with it.
有没有更干净的方法来完成同样的事情?我想避免spyOn,但mockRestore似乎只能使用它。
Thanks!
谢谢!
回答by Raja Jaganathan
For particular spec file, Andreas's is good enough. Below setup will suppress console.logstatements for all test suites,
对于特定的规范文件,安德烈亚斯的就足够了。下面的设置将抑制console.log所有测试套件的语句,
jest --silent
(or)
(或者)
To customize warn, info and debugyou can use below setup
要自定义,warn, info and debug您可以使用以下设置
__tests__/setup.jsorjest-preload.jsconfigured in setupFilesAfterEnv
__tests__/setup.js或jest-preload.js 中配置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.
Jest v24.x 注意:setupTestFrameworkScriptFile 已被弃用,取而代之的是 setupFilesAfterEnv。
module.exports = {
verbose: true,
setupFilesAfterEnv: ["<rootDir>/__tests__/setup.js"],
};
回答by Andreas K?berle
As every test file runs in its own thread there is no need to restore it if you want to disable it for all test in one file. For the same reason you can also just write
由于每个测试文件都在其自己的线程中运行,因此如果您想为一个文件中的所有测试禁用它,则无需恢复它。出于同样的原因,您也可以只写
console.log = jest.fn()
expect(console.log).toHaveBeenCalled();
回答by Constantin
If you wanna do it just for a specific test:
如果你只想做一个特定的测试:
beforeEach(() => {
jest.spyOn(console, 'warn').mockImplementation(() => {});
});
回答by nickb
I found that the answer above re: suppressing console.logacross all test suites threw errors when any other consolemethods (e.g. warn, error) were called since it was replacing the entire global consoleobject.
我发现上面的答案是:console.log在调用任何其他console方法(例如warn,error)时,在所有测试套件中抑制会引发错误,因为它正在替换整个全局console对象。
This somewhat similar approach worked for me with Jest 22+:
这种有点类似的方法对我来说适用于 Jest 22+:
package.json
包.json
"jest": {
"setupFiles": [...],
"setupTestFrameworkScriptFile": "<rootDir>/jest/setup.js",
...
}
jest/setup.js
开玩笑/setup.js
jest.spyOn(global.console, 'log').mockImplementation(() => jest.fn());
Using this method, only console.logis mocked and other consolemethods are unaffected.
使用这种方法,只console.log被mock,其他console方法不受影响。
回答by Michael Liquori
To me a more clear/clean way (reader needs little knowledge of the jest API to understand what is happening), is to just manually do what mockRestore does:
对我来说,一个更清晰/干净的方法(读者需要很少的 jest API 知识来了解正在发生的事情),就是手动执行 mockRestore 所做的:
// at start of test you want to suppress
const consoleLog = console.log;
console.log = jest.fn();
// at end of test
console.log = consoleLog;
回答by Wallace Sidhrée
Another approach is to use process.env.NODE_ENV. This way one can selectively choose what to show (or not) while running tests:
另一种方法是使用process.env.NODE_ENV. 通过这种方式,人们可以在运行测试时有选择地选择要显示(或不显示)的内容:
if (process.env.NODE_ENV === 'development') {
console.log('Show output only while in "development" mode');
} else if (process.env.NODE_ENV === 'test') {
console.log('Show output only while in "test" mode');
}
or
或者
const logDev = msg => {
if (process.env.NODE_ENV === 'development') {
console.log(msg);
}
}
logDev('Show output only while in "development" mode');
This will require this configuration to be placed on package.json:
这将需要将此配置放置在package.json:
"jest": {
"globals": {
"NODE_ENV": "test"
}
}
Note that this approach is not a direct solution to the original question, but gives the expected result as long as one has the possibility to wrap the console.logwith the mentioned condition.
请注意,这种方法不是原始问题的直接解决方案,但只要有可能console.log用上述条件包装 ,就会给出预期的结果。

