paint-brush
How To Test API Requests Using Promisesby@Bren.21
440 reads
440 reads

How To Test API Requests Using Promises

by BrendaJuly 14th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

How To Test API Requests Using Promises is a tutorial on how to deal with API. This guide will help you deal with testing using babel and jest for testing. The tutorial is based on the use of the @babel/polyfill polyfill and the plugin-transform-runtime. The polyfill will emulate a full ES2015+ environment and is intended to be used in an application rather than a library/tool. In order to add the plugin, copy the following code on your babel file: "test"
featured image - How To Test API Requests Using Promises
Brenda HackerNoon profile picture

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: