Mocking API Calls for Snapshot Tests in React | by Petros Demetrakopoulos | Apr, 2022

Tips on how to successfully mock API responses to make use of in snapshot and unit exams in React

Photograph by Artem Sapegin on Unsplash

As software program builders, many occasions, we have to mock knowledge or API calls as a way to write and run automated exams for our code. These exams may be both unit exams following the Given-When-Then precept, that are primarily used to check the right performance of capabilities and lessons, or they are often snapshot exams.

Snapshot exams are a subgroup of unit exams that guarantee a given part may be introduced visually (let’s say a customized React part) matches a given illustration by way of each visible look and content material.

Mocking the information or the API calls a response to fill a customized React part, and it could be an actual ache as many occasions these calls are asynchronous whereas a lot of the unit’s snapshot check sare synchronous (keep in mind the Given-When-Then unit check mannequin).

On this article, I’ll current probably the most environment friendly and self-explanatory method I consider to mock API responses for snapshot exams of customized React elements.

As I’m an enormous fan of TypeScript, I’ll generate a React venture utilizing the TypeScript template. Nevertheless, the identical rules and patterns can be utilized as-is in any React venture with both Javascript or Typescript. So, the primary command I executed on the terminal is the next:

create-react-app mock-api-snapshot-tests --template typescript

With a purpose to obtain a greater venture construction and clearer code, I created a part referred to as TableList, which comprises a desk with some particulars. I used the styled-components library for the styling of any elements I used within the venture which you’ll set up by typing

yarn add styled-components

So, first I declared a styled part that we are going to use later to create the ultimate TableList part, after which, we proceed to the precise implementation of the TableList, which may be seen within the snippet beneath:

We arrange a mock API utilizing https://mockapi.io with a single GET endpoint that returns customers’ objects with three fields every (identify, surname, and electronic mail) for the wants of the venture.

Then we set up axios, a library that makes API calls method simpler for React.

yarn add axios

Again within the App.tsx file, the principle file of our venture, we import axios after which we name the GET endpoint of the API within the useEffect() hook. This impact runs every time the part renders.

It is rather vital to set an empty array because the second argument of the useEffect() hook. In any other case, the part will rerender infinitely and the GET request will fireplace many occasions, leading to rate-limiting error responses from the API.

The snippet of the App.tsx file is proven beneath:

Now, should you run the venture by typing yarn begin within the root listing of the venture, a easy desk will seem and the information will probably be introduced as quickly the API name has a legitimate response.

Screenshot of the React app appropriately proper now

Earlier than transferring on to writing the precise exams, we’ve got to carry out a little bit little bit of configuration.

First, we add the next dependencies:

yarn add --dev jest jest-styled-components @sorts/react-test-renderer ts-jest enzyme-to-json enzyme

Then, we must always add the next discipline within the bundle.json file of the venture:

This configuration ensures that any snapshots will probably be serialized accurately to JSON format. Other than that, within the “scripts > check” discipline of the bundle.json, we must always substitute the worth with “jest”.

Then we must always add a brand new file referred to as jest.setup.ts beneath src listing. The file ought to appear to be this:

Then, we set the tsconfig.json file of the venture to the next:

Lastly, we add a configuration file for babel referred to as babel.config.js.

Now it’s time to write a snapshot check for the App.tsx part. Snapshot exams be sure that a part appears to be like because it ought to and that no breaking adjustments have been made by way of visible look.

Nevertheless, we don’t wish to name the actual API endpoint every time the snapshot check runs for numerous causes. So we’ve got to mock the API responses on the community degree.

First, we create a brand new listing referred to as __tests__ and inside we create a brand new file referred to as App.check.tsx

The code for this file appears to be like like this:

On the primary two traces, we declare any dependencies wanted. On traces 4-13, we declare the mock knowledge we wish to be handed as a response within the API name.

Then, on traces 15-19, we declare the mock get perform of the axios library. Which means that whereas the check runs, axios.get() will use the mocked implementation on line 17 that’s referred to as for this primary time (that is what the mockImplementationOnce perform does).

Lastly, on traces 21–29, the precise testing takes place. This part renders the App part, and it’s anticipated to match snapshot. What’s vital to note right here is that the rendering takes place inside an act wrapper. That is essential, as, through the rendering, there’s a change of state. So doing this inside an act wrapper is obligatory, in any other case, the check will fail.

Now we’re able to run the check by merely typing yarn check within the root listing of the venture.

If every part is about up accurately, we must always see the next output within the terminal:

Profitable snapshot check

The outcomes notify us {that a} new snapshot has been written and that the check handed. So, the subsequent time we run the check, it would test if the newly rendered part matched the snapshot that was generated.

I hope you discover it fascinating, and will probably be helpful in future tasks! You could find the complete venture on this GitHub repository.

More Posts