Skip to content

Instantly share code, notes, and snippets.

@anathematic
Last active July 1, 2021 20:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anathematic/d546788f694bbf9baa08 to your computer and use it in GitHub Desktop.
Save anathematic/d546788f694bbf9baa08 to your computer and use it in GitHub Desktop.
How I'm testing things in React...

Testing in React w/ Karma, Jasmine and some others...

Testing React kinda sucks, here's some techniques I've used to get the basics done quickly... Basically there's three main ingredients I'm using to do my tests in Karma:

This gives me the basic option to be able to click things in the component based on the ref name. React's test utils do provide it's own selectors for this stuff like Capybara but the API sucks / I found this was easier and more productive.

Example:

render() {
  <a onClick={this.derp} ref="derp">derp, creative I know</a>
}

To select this in React I have to select the link, and then fire an event on it (in this case, click):

link = React.findDOMNode(subject.refs.derp);
TestUtils.Simulate.click(link);

jQuery Jasmine is an additional set of matchers to Jasmine I've included, it gives us the Capybara version of expect(page).to have_content with fancier selectors on top:

let html = React.findDOMNode(subject); // important, we need to query on the dom not the React component
expect(html).toContainText("derpy derp derp");

Jasmine's spyOn aka my least favourite way to do tests. Basically using this to catch things like props correctly going up the chain, you need to use a spyOn before doing anything, then you can do a "catch"-like matcher:

spyOn(object, 'cake')
// Do a bunch of stuff, like click a link
expect(object.cake).toHaveBeenCalledWith(attributes);

... and finally, forcing failures from warnings

This little bit here means we raise an exceptional / break the build if we receive a warning in our tests. This has helped a lot in my propsRequired usage / helping clean up the code:

let warn = console.warn;
console.warn = function(warning) {
  if (/(Invalid prop|Failed propType)/.test(warning)) {
    throw new Error(warning);
  }
  warn.apply(console, arguments);
};```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment