如何编写单元测试来覆盖reactjs中的自定义PropTypes?

问题描述 投票:2回答:1

我有一个带有自定义属性的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 unit-testing code-coverage react-proptypes
1个回答
1
投票

我建议取出胖箭头功能并给它一个名字。然后你可以直接从测试中调用它。

© www.soinside.com 2019 - 2024. All rights reserved.