【发布时间】:2021-03-30 14:55:16
【问题描述】:
我正在使用 jest 和 react-testing-library 来测试具有自定义 prop-types 验证器的组件。验证器如下所示:
aspectRatio: (props, propName, componentName) => {
const value = props[propName];
const cleaned = value
.trim()
.replace(/[^0-9:]+/g, ''); // Replace everything but numbers and forward slash.
// Ensure value is “number/number”.
const isCorrectFormat = /^\d+:\d+$/.test(cleaned);
if (!isCorrectFormat) {
return new Error(`Invalid value format “${value}” supplied to “${propName}” prop in “${componentName}” component. Expected something like “3:2”.`);
}
},
我的测试如下所示:
test('throws error when incorrect aspect ratio format passed', () => {
expect(() => {
render(
<Picture
alt="Hello, picture."
aspectRatio="1-1/8"
src="test/books.jpg"
/>,
);
}).toThrowError();
});
验证器在呈现错误的aspectRatio 时按预期工作。我在控制台中收到以下错误:
Warning: Failed prop type: Invalid value format “1-1/8” supplied to “aspectRatio” prop in “Picture” component. Expected something like “3:2”.
但在运行上述测试时,我在终端中收到此消息:
● throws error when incorrect aspect ratio format passed
expect(received).toThrowError()
Received function did not throw
81 | />,
82 | );
> 83 | }).toThrowError();
| ^
84 | spy.mockRestore();
85 | });
86 |
我错过了什么?
【问题讨论】:
-
记录错误与抛出错误
标签: javascript reactjs jestjs react-testing-library