我想知道是否有更好的方法在特定的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似乎只与它一起工作。
如果你使用命令npm test来运行测试,那么在包中更改测试脚本。像下面这样的Json
{
....
"name": "....",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest --silent", // add --silent to jest in script like this
"lint": "eslint ."
},
...
}
或者你可以在测试时直接运行命令npx jest——silent来清除所有日志和错误
对于特定的规格文件,Andreas的已经足够好了。下面的setup将对所有测试套件禁用console.log语句,
jest --silent
(or)
要自定义警告,信息和调试,您可以使用下面的设置
setupFilesAfterEnv中配置的tests/setup.js或jest-preload.js
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"],
};
如果你使用命令npm test来运行测试,那么在包中更改测试脚本。像下面这样的Json
{
....
"name": "....",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest --silent", // add --silent to jest in script like this
"lint": "eslint ."
},
...
}
或者你可以在测试时直接运行命令npx jest——silent来清除所有日志和错误