visit
Writing React Test with React recommend libraries - Jest & Testing Library for React Intermediate users.
In this article, I will explore more advanced concepts in React Testing, I hope you find them helpful for your situations. If you are a beginner in React or new to testing, I would suggest you check out Part 1 Here to have some fundamental knowledge before continue, thanks!
From -
Writing Accessibility Test for every aspect of your app seems very intimidated, but thanks for - A company dedicated on improving software accessibility by offering testing package freely available online, we can now easily leverage the expertise from many senior developers around the world by importing along with Jest Library to test a web app's accessibility.
$ npm install --save-dev jest-axe
$ yarn add --dev jest-axe
With the package install, we can add the Accessibility Test into a project like this:
// App.test.js
import React from 'react';
import App from './App';
import { render } from '@testing-library/react';
import { axe, toHaveNoViolations } from 'jest-axe';
expect.extend(toHaveNoViolations);
describe('App', () => {
test('should have no accessibility violations', async () => {
const { container } = render(<App />);
const results = await axe(container);
expect(results).toHaveNoViolations();
});
});
// ./components/navBar.js
...
<div className="navbar" role='nav'>
...
</div>
...
Check out a List of WAI-ARIA Roles .Replace nav with navigation role as below, the test will pass.
// ./components/navBar.js
...
<div className="navbar" role='navigation'>
...
</div>
...
Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly. -- From
You can put the test on the entire app or one specific component.
They can serve different purposes during the development cycle, you can either use Snapshot Test to ensure your app's UI doesn't change over time or compare the differences between the last snapshot with current output to iterate through your development.Let's take the example of writing a test for the entire App to show you how to write a snapshot test.
// App.test.js
import React from 'react';
import App from './App';
import renderer from 'react-test-renderer';
...
describe('App', () => {
...
test('snapShot testing', () => {
const tree = renderer.create(<App />).toJSON();
expect(tree).toMatchSnapshot();
});
});
If this is the first time this test run, Jest will create a snapshot file(a folder
"__snapshots__"
will create as well) looks similar to this.// App.test.js.snap
// Jest Snapshot v1, //goo.gl/fbAQLP
exports[`App snapShot testing 1`] = `
<div
className="App"
>
<div
className="navbar"
>
....
In this case, you can either press
u
to update the snapshot or change your code to make the test pass again.If you adding a snapshot test at the early stage of development, you might want to turn off the test for a while by adding x in front of the test, to avoid getting too many errors and slowing down the process.
xtest('should have no accessibility violations', async () => {
...
});
Because most of the time, API is hosted by the third party, the time to fetch data is uncontrollable. Besides, for some APIs, given the same parameters, the data come back may vary, which will make the test result unpredictable.For testing with an API, we should:
If you got the ideas, let's dive into the real code practice.
Let's say we want to test the following News page component, where it gets the news from
getNews
API call and render them on the browser.// ./page/News.js
import React, { useState, useEffect } from 'react';
import getNews from '../helpers/getNews';
import NewsTable from '../components/newsTable';
export default () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [errorMsg, setErrorMsg] = useState('');
const subreddit = 'reactjs';
useEffect(() => {
getNews(subreddit)
.then(res => {
if (res.length > 0) {
setPosts(res);
} else {
throw new Error('No such subreddit!');
}
})
.catch(e => {
setErrorMsg(e.message);
})
.finally(() => {
setLoading(false);
});
}, [])
return (
<>
<h1>What is News Lately?</h1>
<div>
{loading && 'Loading news ...'}
{errorMsg && <p>{errorMsg}</p>}
{!errorMsg && !loading && <NewsTable news={posts} subreddit={subreddit} />}
</div>
</>
)
}
First, let's create a
__mocks__
folder at where the API call file located. (In our case, the API call file call getNews.js
), create the mock API call file with the same name in this folder. Finally, prepare some mock data inside this folder.Mock API file (
getNews.js
) should look sth like below -// ./helpers/__mocks__/getNews.js
import mockPosts from './mockPosts_music.json';
// Check if you are using the mock API file, can remove it later
console.log('use mock api');
export default () => Promise.resolve(mockPosts);
// ./helpers/getNews.js
import axios from 'axios';
import dayjs from 'dayjs';
// API Reference - //reddit-api.readthedocs.io/en/latest/#searching-submissions
const BASE_URL = '//api.pushshift.io/reddit/submission/search/';
export default async (subreddit) => {
const threeMonthAgo = dayjs().subtract(3, 'months').unix();
const numberOfPosts = 5;
const url = `${BASE_URL}?subreddit=${subreddit}&after=${threeMonthAgo}&size=${numberOfPosts}&sort=desc&sort_type=score`;
try {
const response = await axios.get(url);
if (response.status === 200) {
return response.data.data.reduce((result, post) => {
result.push({
id: post.id,
title: post.title,
full_link: post.full_link,
created_utc: post.created_utc,
score: post.score,
num_comments: post.num_comments,
author: post.author,
});
return result;
}, []);
}
} catch (error) {
throw new Error(error.message);
}
return null;
};
As we can see from the above codes, a
mock API call
just simply return a resolved mock data, while a real API call
needs to go online and fetch data every time the test run.With the mock API and mock data ready, we now start to write tests.// ./page/News.test.js
import React from 'react';
import { render, screen, act } from '@testing-library/react';
import { BrowserRouter as Router } from "react-router-dom";
import News from './News';
jest.mock('../helpers/getNews'); //adding this line before any test.
// I make this setup function to simplify repeated code later use in tests.
const setup = (component) => (
render(
// for react-router working properly in this component
// if you don't use react-router in your project, you don't need it.
<Router>
{component}
</Router>
)
);
...
Please Note -
jest.mock('../helpers/getNews');
Please add the above code at the beginning of every test file that would possibly trigger the API call, not just the API test file. I make this mistake at the beginning without any notifications, until I add console.log('call real API') to monitor calls during the test.Next, we start to write a simple test to check whether a title and loading message are shown correctly.
// ./page/News.test.js
...
describe('News Page', () => {
test('load title and show status', async () => {
setup(<News />); //I use setup function to simplify the code.
screen.getByText('What is News Lately?'); // check if the title show up
await waitForElementToBeRemoved(() => screen.getByText('Loading news ...'));
});
...
});
...
test('load news from api correctly', async () => {
setup(<News />);
screen.getByText('What is News Lately?');
// wait for API get data back
await waitForElementToBeRemoved(() => screen.getByText('Loading news ...'));
screen.getByRole("table"); //check if a table show in UI now
const rows = screen.getAllByRole("row"); // get all news from the table
mockNews.forEach((post, index) => {
const row = rows[index + 1]; // ignore the header row
// use 'within' limit search range, it is possible have same author for different post
within(row).getByText(post.title); // compare row text with mock data
within(row).getByText(post.author);
})
expect(getNews).toHaveBeenCalledTimes(1); // I expect the Mock API only been call once
screen.debug(); // Optionally, you can use debug to print out the whole dom
});
...
Please Note -
expect(getNews).toHaveBeenCalledTimes(1);
This code is essential here to ensure the API call is only called as expected.When this API call test passes accordingly, we can start to explore something more exciting!
As we all know, an API call can go wrong sometimes due to various reasons, how are we gonna test it?
To do that, we need to re-write our mock API file first.// // ./helpers/__mocks__/getNews.js
console.log('use mock api'); // optionally put here to check if the app calling the Mock API
// check more about mock functions at //jestjs.io/docs/en/mock-function-api
const getNews = jest.fn().mockResolvedValue([]);
export default getNews;
Then we need to re-write the setup function in
News.test.js
file.// ./page/News.test.js
...
// need to import mock data and getNews function
import mockNews from '../helpers/__mocks__/mockPosts_music.json';
import getNews from '../helpers/getNews';
...
// now we need to pass state and data to the initial setup
const setup = (component, state = 'pass', data = mockNews) => {
if (state === 'pass') {
getNews.mockResolvedValueOnce(data);
} else if (state === 'fail') {
getNews.mockRejectedValue(new Error(data[0]));
}
return (
render(
<Router>
{component}
</Router>
))
};
...
Now, let's write the test for API failing.
// ./page/News.test.js
...
test('load news with network errors', async () => {
// pass whatever error message you want here.
setup(<News />, 'fail', ['network error']);
screen.getByText('What is News Lately?');
await waitForElementToBeRemoved(() => screen.getByText('Loading news ...'));
screen.getByText('network error');
expect(getNews).toHaveBeenCalledTimes(1);
})
...
They are just simple test cases for demonstration purposes, in the real-world scenarios, the tests would be much more complex. You can check out more testing examples from my other project .
Photo by on Unsplash
In this article, I followed the best practices Kent C. Dodds suggested in his blog post - published in May 2020, in which you might find my code is slightly different from (I think soon Kent will update the docs as well), but I believe that should be how we write the test in 2020 and onward.
I use both and in-line style in this project to make UI look better, but it is not necessary, you are free to use whatever CSS framework in react, it should not affect the tests.Finally, Testing is an advanced topic in FrontEnd development, I only touch very few aspects of it and I am still learning. If you like me, just starting out, I would suggest you use the examples here or some from my previous article to play around with your personal projects. Once you master the fundamentals, you can start to explore more alternatives on the market to find the best fit for your need.
Here are some resources I recommend to continue learning:
Resources and Article I referenced to finished this article:
Special Thanks for and his course .
I have learned a lot in the past few months from both the course and fellows from the course - and , who help inspire me a lot to finish this testing articles.Below are what I have learned
This post originally posted in .
Previously published at