Testing with Jest

Linked Projects:

Calreact
 
Lesson code - https://github.com/learnetto/calreact-frontend/tree/m10l1-jest

In this module, we’ll look at testing in React.

First, we’ll look at Jest. Jest is one of the most popular Javascript testing libraries which work well with React.

It’s included by default in Create React app. We can run tests by simply running

npm test

It gives us a few options for which tests we want to run. 

Let’s say all and it runs the default test generated when we created the app, App.test.js, and it passes that test.

Let’s have a look at that test. It simply checks if the component renders without crashing.

Jest automatically looks for test files with these naming conventions.

We’ll put all our tests in a separate directory called __tests__.

Now, let’s make a new file for our first test in the tests directory. We’ll call it Appointment.test.js.

And we'll just test the Appointment component.

Let’s start off by copying the code from the example test and change App to appointment.

import React from 'react';
  import ReactDOM from 'react-dom';
  import Appointment from './Appointment';
  import { BrowserRouter as Router } from 'react-router-dom';
  
  it('renders without crashing', () => {
   const div = document.createElement('div');
   ReactDOM.render(<Router><Appointment /></Router>, div);
  });

Now, let’s see if our test passes. No, it fails:

[screenshot 1:17]

That is because our path is not quite right.

It needs to be

 import ReactDOM from 'react-dom';
  import Appointment from '../components/Appointment’

When you now refresh the command line, you will see that our path now found the module, but it’s still failing. The warning says,

[screenshot: 1:33]

So we need to wrap our Appointment component here inside a Router component.

So let’s first import the Router from react-router-dom. We don’t need to import Route. And then let’s add Router around the Appointment component:

import React from 'react';
  import ReactDOM from 'react-dom';
  import Appointment from '../components/Appointment';
  import { BrowserRouter as Router } from 'react-router-dom';
  
  it('renders without crashing', () => {
   const div = document.createElement('div');
   ReactDOM.render(<Router><Appointment /></Router>, div);
  });

And now our test passes.
 
That is our first React test which tests that the Appointment component is rendered correctly, without crashing.

Liked this tutorial? Get more like this in your inbox