如何编写单元测试以覆盖 reactjs 中的自定义 PropTypes?
How to write a unit test to cover custom PropTypes in reactjs?
我有一个带有自定义属性的 reactjs 组件,它实际上只代表允许的扩展列表。
例如,我的组件可以接收像这样的道具:
<CustomComponent allowedTypes={['.pdf', '.txt']} />
道具类型定义如下
CustomComponent.propTypes = {
allowedTypes: PropTypes.arrayOf(
(propValue, key, componentName, location, propFullName) => {
if (!new RegExp(/^\.[^.]+$/).test(propValue[key])) {
return new Error(
`Invalid prop ${propFullName} for component ${componentName}.`
)
}
}
)
我需要用单元测试完全覆盖组件,所以也必须覆盖 prop 类型定义中的代码。
我试过类似的东西,但没用
beforeEach(() => {
console.error = jest.fn()
});
it('should check wrong allowed types', () => {
const wrongAllowedTypes = false
try {
const component = new CustomComponent(Object.assign(defaultProps, { allowedTypes: wrongAllowedTypes } ))
} catch (error) {
expect(console.error).toBeCalled()
}
})
任何想法,提前致谢
我建议把胖箭头函数拿出来给它起个名字。然后你可以直接从测试中调用它。
我有一个带有自定义属性的 reactjs 组件,它实际上只代表允许的扩展列表。
例如,我的组件可以接收像这样的道具:
<CustomComponent allowedTypes={['.pdf', '.txt']} />
道具类型定义如下
CustomComponent.propTypes = {
allowedTypes: PropTypes.arrayOf(
(propValue, key, componentName, location, propFullName) => {
if (!new RegExp(/^\.[^.]+$/).test(propValue[key])) {
return new Error(
`Invalid prop ${propFullName} for component ${componentName}.`
)
}
}
)
我需要用单元测试完全覆盖组件,所以也必须覆盖 prop 类型定义中的代码。
我试过类似的东西,但没用
beforeEach(() => {
console.error = jest.fn()
});
it('should check wrong allowed types', () => {
const wrongAllowedTypes = false
try {
const component = new CustomComponent(Object.assign(defaultProps, { allowedTypes: wrongAllowedTypes } ))
} catch (error) {
expect(console.error).toBeCalled()
}
})
任何想法,提前致谢
我建议把胖箭头函数拿出来给它起个名字。然后你可以直接从测试中调用它。