Before you go, check out these stories!

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

How To Test API Requests Using Promises

Author 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.


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

First, you need to install

 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

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 

. 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

, and other stuff, but we won’t get deeper into that. The
adds to the global scope as well as native prototypes like 
 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": [
    "presets": [


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 => {

And that’s all, Happy Testing! :)



Join Hacker Noon

Create your free account to unlock your custom reading experience.