API testing with Jest

Koen van Gilst
Feb 6, 2017 · 4 min read

Testing async API calls using Jest’s mocking features

Image for post
Image for post

Jest is a great JavaScript testing framework by Facebook. It’s often used for testing React components, but it’s also a pretty good general purpose testing framework. In this tutorial I’ll give a quick and simple demo of it’s mocking capabilities for testing async functions.

This article was also published on my own personal blog.

Purpose of mocking

Mocking async function (like API calls) instead of testing with a real API is useful for a couple of reasons:

  • It’s faster: you don’t have to wait until the API response comes in and you don’t have to deal with rate limits.

Setting up Jest

Configuring Jest isn’t all that difficult, but to get started quickly I’m using the official starter kit by Facebook, create-react-app. This comes with a working Jest configuration out of the box!

Install the create-react-app and create the app:

yarn global add create-react-app

create-react-app mocking-with-jest
cd mocking-with-jest/
yarn start

This should open a browser window with a spinning React logo.

Now start the Jest testing environment:

yarn test

You should see something like this:

Image for post
Image for post

Congratulations, you’ve now got Jest up and running and are ready to start writing some tests!

Adding the API

We’ll be using rest.js for the making the API requests. Rest.js works well in the browser and Node.js.

yarn add rest

Create a new folder api in the folder src and add the file github.js with the following code:

Then also add request.js with the following code:

You’re now ready to make API requests using: github.getUser(‘vnglst’). Let’s test this quickly in the browser. Replace the original contents in the file App.js with the following code:

Use yarn start to open up a browser and see the result. You should see a simple list with my profile data. It works!

Writing tests

We’re now ready to write some tests. Let’s first try to unit test the function getUser. Create a folder __tests__ and in this folder a file github.test.js with the following code:

Start Jest using yarn test and you should see the following error message:

Image for post
Image for post

What’s happening here? It turns out that using our getUser function in a Node environment (which Jest is using to run the tests) makes our request fail. So even though our function works in the browser, it fails in our tests! Would could try and fix this, by adding a User-Agent header when we’re running this in a Node environment, but mocking would now be a better solution. Let’s set this up!

Creating a mock

Create a folder __mocks__ and in this folder a file request.js (this will be the mocked version of request.js in the parent folder):

The mocked function expects a userId.json (i.e. vnglst.json) file in a folder __mockData__. I’ve used my own Github username and data as an example here, but you can add as many example data as you need for your tests:

To let Jest mock the request module, you have to add the following line to github.test.js file:

jest.mock(‘../request’)

Now the simple unit test should pass and you’re ready to write more complicated tests!

I hope you enjoyed this tutorial and feel free to ask me any questions. You can find me on Twitter as @vnglst. The source code of this tutorial can be found here: https://github.com/vnglst/mocking-with-jest

This tutorial is based upon the async example by the creators of Jest (and their example is probably better 😂). Be sure to also check out their other examples.

BONUS: testing using async/await

If you’re using the create-react-app you can also use async/await to write your tests. This definitely makes your tests easier to write and more readable:

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

Image for post
Image for post

HackerNoon.com

#BlackLivesMatter

Sign up for Get Better Tech Emails via HackerNoon.com

By HackerNoon.com

how hackers start their afternoons. the real shit is on hackernoon.com. Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Koen van Gilst

Written by

JavaScript Developer | M.A. in Philosophy | https://github.com/vnglst

HackerNoon.com

Elijah McClain, George Floyd, Eric Garner, Breonna Taylor, Ahmaud Arbery, Michael Brown, Oscar Grant, Atatiana Jefferson, Tamir Rice, Bettie Jones, Botham Jean

Koen van Gilst

Written by

JavaScript Developer | M.A. in Philosophy | https://github.com/vnglst

HackerNoon.com

Elijah McClain, George Floyd, Eric Garner, Breonna Taylor, Ahmaud Arbery, Michael Brown, Oscar Grant, Atatiana Jefferson, Tamir Rice, Bettie Jones, Botham Jean

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface.

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox.

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic.

Get the Medium app