Easy React Unit Testing using Jest & React Testing library — Part2

Amrut Sabale
2 min readMay 24, 2021

Best way to write unit tests in React

I often see people write super complicated tests in React. The main reason is they don’t know that they can mock out any component & library with Jest.

This is part 2 of react testing library articles. Here is part 1 link. Let’s see how we can write unit test with Asynchronous HTTP API call. Most of developers find it difficult.

Photo by Jexo on Unsplash

Asynchronous HTTP API call

There are two ways

  1. Using Jest mocking
  2. Using Mock Service Worker(MSW)

1. Using Jest mocking

Let’s create Todo react app. First will make simple GET request for todos on onclick of ‘Load todos’ button and display them using table.

Now let’s write unit test in Todo.test.js file for fetching all todos correctly.

Here first we have mocked axios GET request using Jest mocking. If you run this test then test will successfully pass. hence Our first todo, “Test1 delectus aut autem” is displayed correctly as per our mock response.

2. Using Mock Service Worker(MSW)

Mock service worker is used to mock requests on the network level. Run the following command in your project’s root directory.

$ npm install msw --save-dev
# or
$ yarn add msw --dev

Let’s take another similar example, make simple GET request for posts on onclick of ‘Load posts’ button and display them using table.

Now let’s write unit test in Post.test.js file for fetching all posts correctly.

Here setupServer function from msw will mock an API request that our component makes. If you run this test then test will successfully pass.

Thank you! Now try this in your projects. Here is Github link for above project. I hope this article helped you.

If you enjoyed this article, please recommend and share it! 🙂

--

--

Amrut Sabale

Senior Software Engineer | ReactJS | Javascript | Web | Frontend | TypeScript | NodeJS