Writing React Test with React recommend libraries - Jest & Testing Library for React Intermediate users. Please Note 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! First, let's look at the . Accessibility Test Front-end development is all about visualization and interacting with end-users, Accessibility Test can ensure our apps can reach as many as possible users out there. Writing 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. From - https://reactjs.org/docs/accessibility.html Accessibility Test Deque Systems Axe Jest-axe $ npm install --save-dev jest-axe or $ yarn add --dev jest-axe With the package install, we can add the into a project like this: Accessibility Test React ; App ; { render } ; { axe, toHaveNoViolations } ; expect.extend(toHaveNoViolations); describe( , () => { test( , () => { { container } = render( // App.test.js import from 'react' import from './App' import from '@testing-library/react' import from 'jest-axe' 'App' 'should have no accessibility violations' async const ); const results = await axe(container); expect(results).toHaveNoViolations(); }); }); < /> App It will help to ensure your FrontEnd Development complies with the latest version of . For example, if you assign a wrong role to your Navigation bar component, it will alert you an error like below: WCAG(Web Content Accessibility Guidelines) ... <div className= role= > ... < // ./components/navBar.js "navbar" 'nav' /div> ... Check out a List of WAI-ARIA Roles . Here Replace nav with navigation role as below, the test will pass. ... <div className= role= > ... < // ./components/navBar.js "navbar" 'navigation' /div> ... As we can see above, this test will help ensure you follow the standard so your app can reach most of the people out there. WCAG(Web Content Accessibility Guidelines) Second, adding a . Snapshot Test Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly. -- From Jest . 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 React ; App ; renderer ; ... describe( , () => { ... test( , () => { tree = renderer.create( // App.test.js import from 'react' import from './App' import from 'react-test-renderer' 'App' 'snapShot testing' const ).toJSON(); expect(tree).toMatchSnapshot(); }); }); < /> App If this is the first time this test run, Jest will create a snapshot file(a folder will create as well) looks similar to this. "__snapshots__" exports[ ] = // App.test.js.snap // Jest Snapshot v1, https://goo.gl/fbAQLP `App snapShot testing 1` ` <div className="App" > <div className="navbar" > .... With this test in place, once you make any change over the DOM, the test will fail and show you exactly what is changed in a prettified format, like the output below: In this case, you can either press to update the snapshot or change your code to make the test pass again. u 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 Third, let's see how to test a UI with an API call. It is fairly common now a frontend UI has to fetch some data from an API before it renders its page. Writing tests about it becomes more essential for the Front End development today. First, let's look at the process and think about how we can test it. When a condition is met (such as click on a button or page loaded), an API call will be triggered; When data come back from API, usually response need to parse before going to next step (optional); When having proper data, the browser starts to render the data accordingly; On the other hand, if something goes wrong, an error message should show up in the browser. In FrontEnd development, we can test things like below: Whether the response comes back being correctly parsed? whether the data is correctly rendered in the browser in the right place? Whether the browser show error message when something goes wrong? However, we should not: Test the API call Call the real API for testing 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: Use Mock API for testing and return fack data Use fake data to compare UI elements to see if they match Let's say we want to test the following component, where it gets the news from API call and render them on the browser. If you got the ideas, let's dive into the real code practice. News page getNews React, { useState, useEffect } ; getNews ; NewsTable ; () => { [posts, setPosts] = useState([]); [loading, setLoading] = useState( ); [errorMsg, setErrorMsg] = useState( ); subreddit = ; useEffect( { getNews(subreddit) .then( { (res.length > ) { setPosts(res); } { ( ); } }) .catch( { setErrorMsg(e.message); }) .finally( { setLoading( ); }); }, []) ( <h1>What is News Lately?</h1> <div> {loading && 'Loading news ...'} {errorMsg && <p>{errorMsg}</p>} {!errorMsg && !loading && <NewsTable news={posts} subreddit={subreddit} />} </div> </> ) } // ./page/News.js import from 'react' import from '../helpers/getNews' import from '../components/newsTable' export default const const true const '' const 'reactjs' => () => res if 0 else throw new Error 'No such subreddit!' => e => () false return <> First, let's create a folder at where the API call file located. (In our case, the API call file call ), create the mock API call file with the same name in this folder. Finally, prepare some mock data inside this folder. __mocks__ getNews.js file ( ) should look sth like below - Mock API getNews.js mockPosts ; .log( ); () => .resolve(mockPosts); // ./helpers/__mocks__/getNews.js import from './mockPosts_music.json' // Check if you are using the mock API file, can remove it later console 'use mock api' export default Promise Vs. Real API Call - axios ; dayjs ; BASE_URL = ; (subreddit) => { threeMonthAgo = dayjs().subtract( , ).unix(); numberOfPosts = ; url = ; { response = axios.get(url); (response.status === ) { response.data.data.reduce( { result.push({ : post.id, : post.title, : post.full_link, : post.created_utc, : post.score, : post.num_comments, : post.author, }); result; }, []); } } (error) { (error.message); } ; }; // ./helpers/getNews.js import from 'axios' import from 'dayjs' // API Reference - https://reddit-api.readthedocs.io/en/latest/#searching-submissions const 'https://api.pushshift.io/reddit/submission/search/' export default async const 3 'months' const 5 const ` ?subreddit= &after= &size= &sort=desc&sort_type=score` ${BASE_URL} ${subreddit} ${threeMonthAgo} ${numberOfPosts} try const await if 200 return ( ) => result, post id title full_link created_utc score num_comments author return catch throw new Error return null As we can see from the above codes, a just simply return a resolved mock data, while a needs to go online and fetch data every time the test run. mock API call real API call With the mock API and mock data ready, we now start to write tests. React ; { render, screen, act } ; { BrowserRouter Router } ; News ; jest.mock( ); setup = ( render( <Router> {component} < // ./page/News.test.js import from 'react' import from '@testing-library/react' import as from "react-router-dom" import from './News' '../helpers/getNews' //adding this line before any test. // I make this setup function to simplify repeated code later use in tests. const ( ) => component // for react-router working properly in this component // if you don't use react-router in your project, you don't need it. /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. ... describe( , () => { test( , () => { setup( // ./page/News.test.js 'News Page' 'load title and show status' async ); //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 ...')); }); ... }); < /> News With the mock API being called and page rendering as expected. We can now continue to write more complex tests. ... test( , () => { setup( 'load news from api correctly' async ); 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 }); ... < /> News 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. .log( ); getNews = jest.fn().mockResolvedValue([]); getNews; // // ./helpers/__mocks__/getNews.js console 'use mock api' // optionally put here to check if the app calling the Mock API // check more about mock functions at https://jestjs.io/docs/en/mock-function-api const export default Then we need to re-write the setup function in file. News.test.js ... mockNews ; getNews ; ... setup = { (state === ) { getNews.mockResolvedValueOnce(data); } (state === ) { getNews.mockRejectedValue( (data[ ])); } ( render( )) }; ... // ./page/News.test.js // need to import mock data and getNews function import from '../helpers/__mocks__/mockPosts_music.json' import from '../helpers/getNews' // now we need to pass state and data to the initial setup const ( ) => component, state = , data = mockNews 'pass' if 'pass' else if 'fail' new Error 0 return {component} < > Router </ > Router I pass the default values into the setup function here, so you don't have to change previous tests. But I do suggest pass them in the test instead to make the tests more readable. Now, let's write the test for API failing. ... test( , () => { setup( // ./page/News.test.js 'load news with network errors' async // pass whatever error message you want here. , 'fail', ['network error']); screen.getByText('What is News Lately?'); await waitForElementToBeRemoved(() => screen.getByText('Loading news ...')); screen.getByText('network error'); expect(getNews).toHaveBeenCalledTimes(1); }) ... < /> News Finally, you can find the complete test code from . here Please Note 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 . here Photo by on ThisisEngineering RAEng Unsplash Final words In this article, I followed the best practices 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. Kent C. Dodds Common mistakes with React Testing Library Test-Library Example 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. styled-component Finally, 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 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. Testing my previous article Here are some resources I recommend to continue learning: Testing from Create React App Which Query should I use From Testing Library More examples from Testing Library Write Test for Redux from Redux.js Unit Test From Gatsby.js from . Effective Snapshot Testing Kent C.Dodds Resources and Article I referenced to finished this article: By . Inside a dev’s mind — Refactoring and debugging a React test Johannes Kettmann by . Don't useEffect as callback! Johannes Kettmann by . Common mistakes with React Testing Library Kent C.Dodds by . Fix the not wrapped act warning Kent C.Dodds . Accessibility From React . Axe for Jest Special Thanks for Johannes Kettmann and his course ooloo.io . 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. Martin Kruger ProxN Below are what I have learned Creating pixel-perfect designs Planning and implementing a complex UI component Implement data fetching with error handling Debugging inside an IDE Writing integration tests Professional Git workflow with pull requests Code reviews Continuous integration This is as the outcome. the Final finishing project This post originally posted in Dev.to . Previously published at https://dev.to/kelvin9877/how-to-write-tests-for-react-in-2020-part-2-26h