How to test a React component propTypes validation

时光总嘲笑我的痴心妄想 提交于 2019-12-13 03:36:09

问题


How can I unit test the propTypes validation of a React component for PropTypes.shape?

My component propTypes validation:

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

My unit test:

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
      );
  })
})

回答1:


Though I don't see the point of unit-testing this you could do the following:

Export your shape as different object

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

and make a unit test for it.

Or more general approach would be to use sinon to spy on console.error and do component render with invalid properties to see it calls your spy

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
})


来源:https://stackoverflow.com/questions/45736470/how-to-test-a-react-component-proptypes-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!