问题
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