Node.js Tests: Mocking HTTP Requests

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.

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.

Free Node eBook

Build your first Node apps and learn server-side JavaScript.

📧

Nice!

Check your email to confirm your subscription.

const expect =require('chai').expect;const getUser =require('../index').getUser;describe('Get User tests',()=>{it('Get a user by username',()=>{returngetUser('octocat').then(response =>{//expect an object backexpect(typeof response).to.equal('object');//Test result of name, company and location for the responseexpect(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!

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.

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.