Sitemap
Ruth Newman

Ruth Newman

Testing with React

4 min readJul 7, 2019
Press enter or click to view image in full size
React and Jest a fitting pair

Good developers practice test driven development. React is a popular JavaScript framework (or library, to be more exact).

In my efforts to continue to become a better developer, I have both been exercising my JavaScript fundamentals, as well as using React when the project suits the functionality and ease that it brings.

I have learnt a little about testing in JavaScript, mostly with Mocha and Jest. I’d yet to combine this with testing in React, and thought there’s no time like the present.

Whilst I practice principles of test driven development in building my projects, I need to become habitualised into adding automated unit testing (or other kinds of testing) from the beginning, not seeing them as a luxury to be added later, or only suitable for larger or more collaborative projects. Testing is suitable (and beneficial!) for all kinds of projects,

Getting good at building tests (using tools such as the Jest test framework — which also works very well with React), will save you time, stress and identify errors you can fix before they become even larger problems. So in short — its worth the small amount of effort. If you’re happy to go figure it out entirely yourself — have at it, you can find the documentation here. Either way, its a useful and extensive resource to turn to.

Installing Jest (locally) happens with a familiar command:

npm install --save-dev jest

Or with yarn:

yarn add --dev jest

In your project’s package.json file, you want to add to the scripts —

"scripts": {
"test": "jest"
}

This command will allow you to run your test suite (but you might want to actually add some tests first!). Any tests you want to add should be saved in files ending with ‘.test.js’ (e.g. you might have one called App.test.js created for you if you used create-react-app to start your React project).

The syntax for a test looks pretty much the same for a React project as with any other JS project — it starts with the syntax test itself, takes a string as its first argument (a description of what the test should do), and then an arrow function as the second argument.

Get Ruth Newman’s stories in your inbox

Join Medium for free to get updates from this writer.

For example, if you have an array of (arbitrarily) — ten restaurants, and you want the user to be able to filter by cuisine. Three are Japanese restaurants, and so if the user selects Japanese cuisine, they should end up with three restaurants in the results.

test("should filter restaurants by cuisine, selecting Japanese restaurants only", () => {
const result = filterByCuisine("Japanese")
})

For that example to work I’d need a function called filterByCuisine that actually does that, such as the below:

const filterByCuisine = (cuisine) => {
let filteredRestaurants = this.state.restaurants.filter((restaurant) => restaurant.cuisine === cuisine);
return filteredRestaurants;}

This test will now pass (you’ll want to run ‘npm run test’ or ‘yarn test’ depending on which you’re using, but it’s bound to, it doesn’t really test anything yet. So it’s worth adding a little more to that first test above to check something about the result. If, in this case the result is an array, we could test its length (and that it’s three like the number of restaurants we are looking for).

test("should filter restaurants by cuisine, selecting Japanese restaurants only", () => {
const result = filterByCuisine("Japanese");
if (result.length !== 3) {
throw new Error("Does not select the Japanese restaurants. Expect 3 restaurants, instead you have ${result.length}")
} })

You could also refactor this to a more traditional syntax as below:

test("should filter restaurants by cuisine, selecting Japanese restaurants only", () => {
const result = filterByCuisine("Japanese");
expect(result.length).toBe(3);
})

If my restaurant finding application (with its limited 10 restaurant API), is made up of different components, I might have components such as a Header or Footer component.

For a Header component, for example, I might want to test this too! Test it renders correctly and so forth. Well like for most things there is a library that makes things quicker and easier to do this: react-test-renderer. As it mentions in the description of the package, this enables you to take a ‘snapshot’ of the DOM tree to check it has rendered properly. You’ll want to import the shallow renderer as below:

import React from 'react';import ReactShallowRenderer from 'react-test-renderer/shallow';import Header from '../../Header';test('should render Header component correctly', () => {
const renderer = new ReactShallowRenderer();
renderer.render(<Header />);
expect(renderer.getRenderedOutput()).toMatchSnapshot();
});

This will create an initial snapshot of what the initial rendered version of the header component looks like, if this changes at any point, it will no longer match, and the test will fail.

That is just a couple of the funky things you can do with testing in React, I want to keep exploring this, become increasingly familiar and use testing as a course of habit when building a new application, rather than an extra step I take with each project.

--

--