PropTypes Validation in React + Karma
Bonnie Eisenman
93

What if you want to test for property warnings multiple times? For example:

it('will warn without onPress property', function() {

consoleErrors = ["Warning: Failed propType: Required prop `onPress` was not specified in `KeyPadButton`."];

chai.spy.on(console, 'error');

renderIntoDocument(
<KeyPadButton label=""/>
);

expect(console.error).to.have.been.called.once.with(consoleErrors[0]);
});

it('will warn without label property', function() {

consoleErrors = ["Warning: Failed propType: Required prop `label` was not specified in `KeyPadButton`."];

chai.spy.on(console, 'error');

renderIntoDocument(
<KeyPadButton onPress={ () => {} }/>
);

expect(console.error).to.have.been.called.once.with(consoleErrors[0]);
});

it('will warn without any properties', function() {

consoleErrors = ["Warning: Failed propType: Required prop `onPress` was not specified in `KeyPadButton`.",
"Warning: Failed propType: Required prop `label` was not specified in `KeyPadButton`."];

chai.spy.on(console, 'error');

renderIntoDocument(
<KeyPadButton />
);

expect(console.error).to.have.been.called.with(consoleErrors[0]);
expect(console.error).to.have.been.called.with(consoleErrors[1]);

});

I can’t seem to get the final test to pass, as React only fires these warnings once per element:

if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;

var addendum = getDeclarationErrorAddendum();
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : undefined;
}

Can’t seem to find a way to safely clear “loggedTypeFailures” as it is protected by closure scope.