Testing Components
We'll test components in our Weather app that's built with React and Redux.
We'll cover the following...
When testing our components, the one thing we want to verify is that they render the same output as last time the test was ran. Since they are bound to change very often, more specific tests are more of a burden than a help. If the test fails, but we’ve manually verified the new output is correct we should be able to quickly tell that to our testing framework without much effort.
Exactly for that purpose, Jest recently added support for component snapshots. Component snapshots are generated on the first test run and saved in files in your project. They should be checked into version control if you have one, and code reviews should include them.
By having those snapshots after the first test run, we can immediately verify if our component output was changed. If any change happened and we manually verified the new version is correct we can run jest -u
to update the existing snapshots!
Setup
To render the components without opening a browser we’ll have to install the react-test-renderer
. It allows us to render the component to a JSON object!
npm install --save-dev react-test-renderer
Let’s create a new file and add the basic testing code. We’ll be starting with the App component, so import
that for now:
// __tests__/components.test.js
import React from 'react';
import renderer from 'react-test-renderer';
import App from '../App';
describe('components', function() {
describe('<App />', function() {
});
});
The thing we want to verify in our App
component is that it renders without throwing an error and taking a snapshot so we know when the output changes. Let’s add an it
to that effect:
// __tests__/components.test.js
import React from 'react';
import renderer from 'react-test-renderer';
import App from '../App';
describe('components', function() {
describe('<App />', function() {
it('renders correctly', function() {
});
});
});
Let’s now create a renderer, render our <App />
component to JSON and expect that to match the snapshot:
// __tests__/components.test.js
import React from 'react';
import renderer from
...