In my previous blog i explored “Testing a RESTful API using Supertest”
In this post i will look at how an API can be mocked using a node package called nock.
Mocking API’s can be incredibly useful for a number of scenarios:
- You want to test different responses easily
- You want to mock a third party system which you don’t control
- You want to simulate some negative scenarios such as a system being unavailable or responding unexpectedly.
In this example we’ll be using the following:
- nock – “Nock is an HTTP mocking and expectations library for Node.js. Nock can be used to test modules that perform HTTP requests in isolation.”
- Supertest – “High-level abstraction module for testing HTTP”
Mocking an API
nock allows you to intercept an API call and respond with a programmed response. The documentation on npm is excellent. It provides many examples of how it can be used from simple responses through to the more complex.
I will be mocking the following API http://postcodes.io/ – Post Code & Geolocation API for the UK.
Mocking a simple response
Here is a simple example that returns a 200 OK and a simple JSON response
Simulating a Time Out
A good example where Mocking API’s can be useful is simulating a Time Out. Good for us is that nock provides this capability out of the box.
In the below example I’m simulating a 10 second delay.
NOTE: Mocha has a default timeout of 2000ms so you also need to increase the mocha timeout otherwise it will kick in before your mocked response completes.
Mocking from a JSON file
To keep your mock responses organized you may want to store them in JSON files to enable reuse and reduce maintenance effort.
According to the nock documentation support should come this with the function .replyWithFile. I tried to use this but found that the body property was not populated in the response.
As a workaround i used node to read in the file and assign it to a variable i could then specify in my mock response.
The JSON file containing the mocked response:
The examples i have included are pretty simple but can be incredibly useful when testing an API. The nock documentation has a whole host of other examples including:
- Setting and Reading Headers
- Reading request body
- Using regular expressions
- Replying with errors
I will definitely be exploring these features further.