How to test Node.js: Mocking HTTP request

How to test Node.js: Mocking HTTP request

How to test Node.js: Mocking HTTP request ... Writing tests for an application that relies on external services, say, a RESTful API, is challenging. ✈️✈️✈️✈️✈️

More often than not, an external resource may require authentication, authorization or may have a rate limiting.Hitting an endpoint for a service hosted in a service like AWS as part of testing would also incur extra charges.

This quickly goes out of hand when you are running tests a couple of times a day as a team, as well as part of continous integration. Nock, a HTTP mocking and expectations library for Node.js can be used to avoid this.

Objectives


Table of Contents

  • Objectives
  • Setting Up The Project
  • Creating A Node.js App To Test
  • Testing: The Wrong Way
  • Testing: The Right Way
  • Conclusion

By the end of this post, we will have achieved the following.

  • Written a simple Node.js application that makes a HTTP request to an external endpoint.
  • Write tests for the application
  • Mock the requests in the test.
Setting Up The Project

To get started, create a simple Node.js application by creating an empty folder and running npm init.

mkdir nock-tests
cd nock-tests
npm init

Installing the packages

Next, we will install the following packages for our application and testing environment.

  • Axios - A Promise based HTTP client for the browser and node.js
  • Mocha - A popular Node.js testing framework.
  • Chai - A BDD / TDD assertion library for Node.js
  • Nock - A HTTP mocking and expectations library for Node.js
npm install --save axios
npm install --save-dev mocha chai nock

Setting up tests

Our tests will live inside a test directory, Go ahead and create a test directory and create our first test.

mkdir test
touch test/index.test.js

Our first test should be pretty straightforward. Assert that true is, well, true.

/test/index.test.js

const expect = require('chai').expect;

describe('First test', () => {
it('Should assert true to be true', () => {
expect(true).to.be.true;
});
});

To run our test, we could run the mocha command from our node_modules but that can get annoying. We are instead going to add it as an npm script.

/package.json

{
"name": "nock-tests",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "node_modules/.bin/mocha"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.16.2"
},
"devDependencies": {
"chai": "^4.0.2",
"mocha": "^3.4.2",
"nock": "^9.0.13"
}
}

At this point, running npm test on your command-line should give you the following result.

$ npm test > [email protected] test /Users/username/projects/nock-tests > mocha First test ✓ Should assert true to be true 1 passing (15ms)

We obviously don't have any tests making requests, or a useful request for that matter, but we will be changing that.

Creating A Node.js App To Test

Let's go ahead and write a simple function that makes a HTTP request to the Github API to get a user by username. Go ahead and create an index.js file in the root and add the following code.

/index.js

const axios = require('axios');

module.exports = {
getUser(username) {
return axios
.get(https://api.github.com/users/${username})
.then(res => res.data)
.catch(error => console.log(error));
}
};

Testing: The Wrong Way

Our test will assert that the request made returns an object with specific details. Replace the truthy test we created earlier with the following test for our code.

const expect = require('chai').expect;

const getUser = require('../index').getUser;

describe('Get User tests', () => {
it('Get a user by username', () => {
return getUser('octocat')
.then(response => {
//expect an object back
expect(typeof response).to.equal('object');

    //Test result of name, company and location for the response
    expect(response.name).to.equal('The Octocat')
    expect(response.company).to.equal('GitHub')
    expect(response.location).to.equal('San Francisco')
  });

});
});

Let's break down the test.

  • We import the getUser method from /index.js.
  • We then call the function and assert that we get an object back and that the user's name, company and location match.

This should pass on running the test by actually making a request to the Github API. Let's fix this!

Testing: The Right Way
Nock works by overriding Node's http.request function. Also, it overrides http.ClientRequest too to cover for modules that use it directly.

With Nock, you can specify the HTTP endpoint to mock as well as the response expected from the request in JSON format. The whole idea behind this is that we are not testing the Github API, we are testing our own application. For this reason, we make the assumption that the Github API's response is predictable.

To mock the request, we will import nock into our test and add the request and expected response in the beforeEach method.

/test/index.test.js

const expect = require('chai').expect;
const nock = require('nock');

const getUser = require('../index').getUser;
const response = require('./response');

describe('Get User tests', () => {
beforeEach(() => {
nock('https://api.github.com')
.get('/users/octocat')
.reply(200, response);
});

it('Get a user by username', () => {
return getUser('octocat')
.then(response => {
//expect an object back
expect(typeof response).to.equal('object');

    //Test result of name, company and location for the response
    expect(response.name).to.equal('The Octocat')
    expect(response.company).to.equal('GitHub')
    expect(response.location).to.equal('San Francisco')
  });

});
});

The expected response is defined as an export in a separate file.

/test/response.js

module.exports = { login: 'octocat',
id: 583231,
avatar_url: 'https://avatars0.githubusercontent.com/u/583231?v=3',
gravatar_id: '',
url: 'https://api.github.com/users/octocat',
html_url: 'https://github.com/octocat',
followers_url: 'https://api.github.com/users/octocat/followers',
following_url: 'https://api.github.com/users/octocat/following{/other_user}',
gists_url: 'https://api.github.com/users/octocat/gists{/gist_id}',
starred_url: 'https://api.github.com/users/octocat/starred{/owner}{/repo}',
subscriptions_url: 'https://api.github.com/users/octocat/subscriptions',
organizations_url: 'https://api.github.com/users/octocat/orgs',
repos_url: 'https://api.github.com/users/octocat/repos',
events_url: 'https://api.github.com/users/octocat/events{/privacy}',
received_events_url: 'https://api.github.com/users/octocat/received_events',
type: 'User',
site_admin: false,
name: 'The Octocat',
company: 'GitHub',
blog: 'http://www.github.com/blog',
location: 'San Francisco',
email: null,
hireable: null,
bio: null,
public_repos: 7,
public_gists: 8,
followers: 1840,
following: 6,
created_at: '2011-01-25T18:44:36Z',
updated_at: '2017-07-06T21:26:58Z' };

To test that this is the actual response expected in the test, try editing one of the fields in the response object and run the test again. The tests should fail.

In my case, I will be changing the name value to Scotch. You should get the error below.


Conclusion

We have only scratched the surface on what you can do with nock. It has a very detailed documentation on how to use it and it is worth exploring. For instance, If you are writing tests that involve error handling, you could mock error responses with an error message.

nock('http://www.google.com')
.get('/cat-poems')
.replyWithError('something awful happened');

Happy testing!

========================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ The Complete Node.js Developer Course (3rd Edition)

☞ Angular & NodeJS - The MEAN Stack Guide

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ Docker for Node.js Projects From a Docker Captain

☞ Intro To MySQL With Node.js - Learn To Use MySQL with Node!

☞ Node.js Absolute Beginners Guide - Learn Node From Scratch

☞ React Node FullStack - Social Network from Scratch to Deploy

☞ Selenium WebDriver - JavaScript nodeJS webdriver IO & more!

☞ Complete Next.js with React & Node - Beautiful Portfolio App

☞ Build a Blockchain & Cryptocurrency | Full-Stack Edition

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.

Difference between AngularJS, React, Ember, Backbone, and Node.js.

The most common thing between all of them is that they are Single Page Apps. The SPA is a single page where much of the information remains the same and only some piece of data gets modified when you click on other categories/option.

Node.js Tutorial for Beginners | Node.js Crash Course | Node.js Certification Training

This courseis designed for professionals who aspire to be application developers and gain expertise in building real-time, highly-scalable applications in Node.js. The following professionals can go for this course :

Why learn Node.js?

Node.js uses JavaScript - a language known to millions of developers worldwide - thus giving it a much lower learning curve even for complete beginners. Using Node.js you can build simple Command Line programs or complex enterprise level web applications with equal ease. Node.js is an event-driven, server-side, asynchronous development platform with lightning speed execution. Node.js helps you to code the most complex functionalities in just a few lines of code...

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Docker for Node.js Projects From a Docker Captain

Intro To MySQL With Node.js - Learn To Use MySQL with Node!

Node.js Absolute Beginners Guide - Learn Node From Scratch

React Node FullStack - Social Network from Scratch to Deploy

Selenium WebDriver - JavaScript nodeJS webdriver IO & more!

Complete Next.js with React & Node - Beautiful Portfolio App

Build a Blockchain & Cryptocurrency | Full-Stack Edition