How to write mock fetch unit test with Jest

Jennet Hydyrova
3 min readDec 27, 2020

Testing is an important part of ensuring that your app works as expected. However, it might be a confusing topic for those who have never written unit tests before. During the final project in bootcamp I had to write my first unit test which was a mock fetch unit test. It had to check whether fetched data was passed correctly to the component or not and to show it in the snapshot of this component. The point of this unit test is to “fake” fetched data and pass this data to the testing environment to avoid calling API in your test directly.

I couldn’t find many resources on this topic and had a hard time writing mock fetch unit test. Therefore, I thought it would be useful to show in this article how I wrote it. I think, it would be useful for junior engineers like myself, who had no prior experience in writing unit tests.

So, let’s start!

Imagine you are fetching articles from some API with a JSON file structure like so

and you are passing it to some component for rendering. If you need to write a test for this component and attempt to write a simple snapshot test, fetched data will not be displayed in the snapshot. Therefore, you would not know if fetched data is being passed and rendered correctly. Here, mock fetch Jest unit test comes in handy.

Let’s say we create a component that fetches articles form some API and renders it as you can see in the example code

Okay, now we need to create a test file. Let’s start by importing necessary files and creating a mock data.

After that, you will need to create a container. beforeEach and afterEach functions are optional. In case you are running multiple tests, it’s required. Otherwise, it’s not but it’s still a good practice to setup and clear up test every time we run it.

The last part of the test will actually pass mock data to the component and create a snapshot with the mock data. Essentially what we do here is we are spying on the method called ‘fetch’ and chaining to it mockImplementation. So, whenever the fetch method is being called, mockImplementation resolves a promise by returning mock data. mockImplementation() function in Jest is used to define a default implementation for the mock function. If you want to define implementation for a single call, you can use mockImplementationOnce(). Please read more about jest.spyOn() here and about mockImplementation() and mockImplementationOnce() here.

Your snapshot test would like like this

Mock fetch unit test with Jest shows us mock data in the snapshot of your component, which helps us to ensure that we are correctly passing fetched data to the component. Read more about test for data fetching here.

Hope it was helpful and you will be able to mock API fetch easily!

--

--

Jennet Hydyrova

Re:Coded Web Development Bootcamp graduate. Interested in front-end and back-end development. My website https://jennethydyrova-portfolio.netlify.app/