wol*_*111 5 javascript reactjs jestjs react-error-boundary
来自错误边界的反应文档:
React 16 会将渲染过程中发生的所有错误打印到开发中的控制台,即使应用程序不小心吞下了它们。
由于上述原因,我在运行测试时遇到了大量不必要的控制台错误。是否可以在 Jest 中隐藏这些内容,而无需嘲笑/监视 console.error?
是的..保持测试输出干净总是一个好主意。没有嘲笑和间谍活动 - 不知道,但这是我的嘲笑间谍版本。
在这种情况下有两个步骤。其中一个非常明显:过滤控制台输出。在测试初始化文件中,它是这样的:
"jest": {
"setupFilesAfterEnv": [
"<rootDir>/jest/setupTests.js"
],
Run Code Online (Sandbox Code Playgroud)
有我的错误和警告过滤代码。
const warningPatterns = [
/componentWillReceiveProps/,
/The `css` function is deprecated/
];
const errorPatterns = [
/Should be caught by ErrorBoundary/,
]
global.console = {
...global.console,
warn: (...args) => {
if (warningPatterns.some(pattern => args.some(line =>
pattern.test(line)))) {
return;
}
originalWarn(...args);
},
error: (...args) => {
const canSkip = args.some(line => {
return errorPatterns.some(pattern => {
return pattern.test(line?.message || line);
});
});
if (canSkip) {
return;
}
originalError(...args);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,如果您有 JSDOM,则必须模拟虚拟控制台。我更愿意在测试中执行此操作,因为您可能没有太多边界测试。
it('should catch Errors', () => {
const virtualConsole = window._virtualConsole;
const originalEmit = virtualConsole.emit;
const emit = jest.spyOn(virtualConsole, 'emit');
emit.mockImplementation(function (type, error) {
// you may skip the type check
if (type === 'jsdomError' && error.detail.message === 'Should be caught by ErrorBoundary') {
return;
}
return originalEmit.call(this, type, error);
});
const { getByText } = render(() => throw new Error('Should be caught by ErrorBoundary'));
expect(getByText('Should be caught by ErrorBoundary').toBeInTheDocument();
emit.mockRestore();
});
Run Code Online (Sandbox Code Playgroud)