Reputation: 1086
I'm trying to test a React component with some propType logic. The component should take a myprop
prop that should match {value: [anything]}
.
The first test works, but the second (which is exactly the same code) doesn't.
Any idea why ?
EDIT : I think it's React that does not call console.error()
every time, but only once. Probably to avoid spamming the console...
import React from 'react';
import chai, { expect } from 'chai';
import chaiEnzyme from 'chai-enzyme'
import { shallow } from 'enzyme';
chai.use(chaiEnzyme());
class MyComponent extends React.Component {
render() {
return (
<div>
{this.props.myprop.value}
</div>
);
}
}
MyComponent.propTypes = {
myprop: (props, propName, componentName) => {
const prop = props[propName];
if (typeof(prop) !== 'object') {
return new Error(`<${componentName}> requires the prop \`${propName}\``);
}
else {
if (typeof(prop.error) === 'undefined' || !prop.error) {
if (typeof(prop.value) === 'undefined') {
return new Error(`<${componentName}> requires the prop \`${propName}\` to have a \`value\` field`);
}
}
}
return null;
},
};
//Mocking console.error to throw propType errors
let console_error = console.error;
console.error = function(warning) {
if (/(Invalid prop|Failed prop type)/.test(warning)) {
throw new Error(warning);
}
console_error.apply(console, arguments);
};
describe('<MyComponent/>', function() {
describe('with invalid `myprop` format', function() {
it('should throw an error', function(done) {
//This test passes
//Execute
const fn = () => shallow(<MyComponent myprop={{}}/>);
//Verify
expect(fn).to.throw(Error, 'requires the prop \`myprop\` to have a \`value\` field');
done();
});
it('should throw an error', function(done) {
//Exactly the same code as above -- does not pass
//Execute
const fn = () => shallow(<MyComponent myprop={{}}/>);
//Verify
expect(fn).to.throw(Error, 'requires the prop \`myprop\` to have a \`value\` field');
done();
});
});
});
Upvotes: 0
Views: 116