Before you go, check out these stories!

0
Hackernoon logoHow To Test API Requests Using Promises by@Bren.21

How To Test API Requests Using Promises

Author profile picture

@Bren.21Brenda

Dealing with testing can be hard sometimes, especially if you’re not too experienced in javascript. So, if you’re learning how to deal with API and now you want to start with testing, this guide will help you with it.

Install

For this tutorial, I will assume that we already have a javascript project with babel and jest for testing.

First, you need to install

@babel/plugin-transform-runtime
 in your current project. This plugin will avoid duplication across your compiled output.

Another purpose of the transformer is to create a sandboxed environment for your code. If you directly import

@babel/polyfill 
and the built-ins it, will pollute the global scope.

npm install — save-dev @babel/plugin-transform-runtime
npm install — save @babel/runtime

Then, you need to install 

polyfill
. Which will emulate a full ES2015+ environment and is intended to be used in an application rather than a library/tool.

Also, it lets you use

Promise
, and other stuff, but we won’t get deeper into that. The
polyfill 
adds to the global scope as well as native prototypes like 
String
 in order to do this.

npm install — save @babel/polyfill

Finally, in order to add the runtime plugin, copy the following code on your babel file:

“env”: { “test”: { “plugins”: [ “@babel/plugin-transform-runtime” ] } },

So now, your babel file will look like this:

{
    "env": {
        "test": {
        "plugins": [
            "@babel/plugin-transform-runtime"
        ]
        }
    },
    "presets": [
        "@babel/preset-env"
    ]
}

Test

Now, In your testing page add this line on the top, to ensure the polyfills are loaded first:

import ‘@babel/polyfill’;

Now that you have all. You just need to add your test like usually, and you’ll get something like the code below:

test('Test if data is being received from API', () => {
  const api = request.checkData();
  // CheckData is a basic function inside './mocks/apiRequestMock'
  api.then(result => {
    expect(result[0].user).toBe('user1');
  });
}); 

And that’s all, Happy Testing! :)

Resources:

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!