【问题标题】:How to test a React component propTypes validation如何测试 React 组件 propTypes 验证
【发布时间】:2018-01-25 22:46:45
【问题描述】:

如何对 PropTypes.shape 的 React 组件的 propTypes 验证进行单元测试?

我的组件 propTypes 验证:

MyComponent.propTypes = {
  propA: PropTypes.string.isRequired,
  propB: PropTypes.shape({
    inner1: PropTypes.bool.isRequired,
    inner2: PropTypes.func,
  }).isRequired,
}

我的单元测试:

describe('MyComponent propTypes validation', () => {
  it('validates propA', () => {
    expect(MyComponent.propTypes.propA).toBe(PropTypes.string.isRequired);
  })

  // THIS FAILS. Expected: [Function bound checkType], actual: [Function bound checkType]
  it('validates propB', () => {
    expect(MyComponent.propTypes.propB)
      .toEqual(
        PropTypes.shape({
          inner1: PropTypes.bool.isRequired,
          inner2: PropTypes.func,
        }).isRequired
      );
  })
})

【问题讨论】:

    标签: reactjs unit-testing jestjs react-proptypes


    【解决方案1】:

    虽然我没有看到对此进行单元测试的意义,但您可以执行以下操作:

    将您的形状导出为不同的对象

    // some-descriptive-name-shape.js
    export default {
       inner1: PropTypes.bool.isRequired,
       inner2: PropTypes.func,
    }
    

    并对其进行单元测试。

    或者更通用的方法是使用sinon 监视console.error 并使用无效属性进行组件渲染以查看它调用您的间谍

    let consoleError;
    
    beforeEach(() => {
        consoleError = spyOn(console, 'error');
    });
    
    afterEach(() => {
        consoleError.restore();
    })
    
    it('should warn on empty propB, () => {
       // do shallow render of <MyComponent />
       expect(consoleError.called).toBe(true)
       // etc
    })
    

    【讨论】:

      猜你喜欢
      • 2014-11-25
      • 2018-01-14
      • 2015-09-18
      • 2019-02-15
      • 2018-05-15
      • 2017-04-05
      • 2018-09-17
      • 2020-10-29
      • 1970-01-01
      相关资源
      最近更新 更多