Sitemap
About Codecademy

Lessons learned while teaching the world to code

PropTypes Validation in React + Karma

--

At Codecademy, we use Karma + Jasmine to test our React codebase. We also use PropTypes to document what props each React component expects.

Problem: we weren’t actually validating the PropTypes, so even though we made an effort to keep them clean, warnings kept sneaking in:

PropTypes are important. They’re part of how we document our code, and missing or invalid props are often a sign of lurking bugs.

Note that despite the failing PropTypes, our tests are passing!

We use CircleCI to run our tests, and surface that information in Github. If we could include props validation in our test suite that would be ideal. But it looks like React doesn’t provide any test utilities for prop validation…

It’s not particularly elegant, but our approach spies on console.warn and looks for appropriately formatted log statements.

//react_warnings.js
export default {
watchConsole() {
spyOn(console, ‘warn’);
},
propWarnings() {
let propWarnings = console.warn.calls.all().filter((c) => {
return (c.args &&
c.args.length > 0 &&
/(Invalid prop|Failed propType)/.test(c.args[0]));
});
return propWarnings;
}
}

Then a test might look something like this:

import ReactWarnings from ‘test_helpers/react_warnings’;describe('MyComponent', () => {  beforeEach(ReactWarnings.watchConsole);  it('renders without propWarnings', () => {
TestUtils.renderIntoDocument(
<MyComponent someProp="whatever"/>
);
});
afterEach(() => {
expect(ReactWarnings.propWarnings().length).toBe(0);
});
});

Note that you have to invoke watchConsole before you render the component, if you want to catch render-related warnings.

It’s short, it’s simple, and it works for us.

If you have a different approach for validating PropTypes in React, I’d love to hear it!

--

--

About Codecademy
About Codecademy

Published in About Codecademy

Lessons learned while teaching the world to code

Bonnie Eisenman
Bonnie Eisenman

Written by Bonnie Eisenman

Software eng @ Twitter, author of Learning React Native. http://blog.bonnieeisenman.com/

Responses (4)