What is Nock? and how can i test REST API Using Axios (JS)

Davit Danelia
4 min readSep 15, 2021
Photo by Paul Esch-Laurent on Unsplash

When I was writing APIs in express (node), I had an idea to automate test cases of live APIs; after some research, I obtained some information and understanding, as well as one additional dependency package in my project. 😁🤭

Okey! now lets talk less and write more:)

Firstly, creating new project by terminal using add npm init command:

npm init

After you must add some details about package like this:

You can write there whatever you want. That’s step where our package.json is being created. Add all the details and press enter… Now we have our package.json in root of out directory

Secondly, we must install the axios, chai and nock packages in our project to start working with them.

npm i axios
npm i mocha chai nock -D

I have added -D with mocha/nock/chai cuz i need them in development mode only, now little bit about those packages :

Mocha — is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun.

Click Here for more information

Axios — is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase).

Click Here for more information

Chai — is a BDD / TDD assertion library for [node](http://nodejs.org) and the browser that can be delightfully paired with any javascript testing framework.

Click Here for more information

Nock — is an HTTP server mocking and expectations library for Node.js. Nock can be used to test modules that perform HTTP requests in isolation, i will talk about one of its functionality so if you wanna delve into it:

Click Here

Let’s get back to the main topic. Now, we have packages with right dependencies. Make a folder called “test” in which we will store several API test cases. Create one file and name it for example: api.test.js

const { expect } = require('chai');description('first describe statement', () => {
it('First test, must work sucessfully', ()=> {
expect("David").to.equal("David");
});
});

That’s it, this is how sample test looks like, i have added a simple sample logic whick will test expectation of “David” to be equal to “David”

Now about running our test. That’s where we need mocha. We must add a specific line in a package.json and modify the test line, we must get:

“scripts”: {
“test”: “node_modules/.bin/mocha”
},

Let’s run our sample test, for that we must run this command from our terminal:

npm test

this specific command will go through our test folder and run files with .test extension and give the report of the test run in terminal like this:

Now let’s create at least one API to test it using Nock. Create a file sampleRequest.js in the root package.

const axios = require('axios');module.exports = {
getSampleUser(user) {
return axios
.get(`https://api.github.com/users/${user}`)
.then((result) => result.data)
.catch((err) => console.err(err));
}
};

Thats a API fuction with axios that will fetch the data of the user which we are passing in the function as an argument, now we must also edit the api.test.js file:

const { expect } = require('chai');
const response = require('../mockResponse');
const { getSampleUser} = require('../sampleRequest');
const nock = require('nock');
describe('first describe statement', () => {
beforeEach(() => {
nock('https://api.github.com')
.get('/users/davit')
.reply(200, response);
});
it('It should be true', () => {
return getSampleUser('davit')
.then(response => {
expect (typeof response).to.equal('object');
expect (response.location).to.equal('Tbilisi');
expect (response.id).to.equal(2556493);
});
});
});

about beforeEach and it logic

beforeEach(() => {
nock(‘https://api.github.com')
.get(‘/users/davit’)
.reply(200, response);
});

beforeEach — this method will be executed before each test case begins, for example in my case i check for 200 status code in each test case response

it('It should be true', () => {
return getSampleUser('davit')
.then(response => {
expect (typeof response).to.equal('object');
expect (response.location).to.equal('Tbilisi');
expect (response.id).to.equal(2556493);
});
});

In mocha, it means test case, and it’s functions that contain test case logic. For example, in our test case, I check if the response is object type, the location in the response is “Tbilisi,” and the id is 2556493.

So this is the final code of the test case. We have gotSampleUser function implemented by adding Nock to the APIs with arguments.

In the end, We’ve built the nock for the testing of actual APIs. but forgot to mention, we need one more file with API Response content so we can test and match data with it. Create a new file, mockResponse.js

module.exports = {
"login": "davit",
"id": 2556493,
"node_id": "MDQ6VXNlcjI1NTY0OTM=",
"avatar_url": "https://avatars.githubusercontent.com/u/2556493?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/davit",
"html_url": "https://github.com/davit",
"followers_url": "https://api.github.com/users/davit/followers",
"following_url": "https://api.github.com/users/davit/following{/other_user}",
"gists_url": "https://api.github.com/users/davit/gists{/gist_id}",
"starred_url": "https://api.github.com/users/davit/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/davit/subscriptions",
"organizations_url": "https://api.github.com/users/davit/orgs",
"repos_url": "https://api.github.com/users/davit/repos",
"events_url": "https://api.github.com/users/davit/events{/privacy}",
"received_events_url": "https://api.github.com/users/davit/received_events",
"type": "User",
"site_admin": false,
"name": "Davit",
"company": "Web Intelligence",
"blog": "",
"location": "Tbilisi",
"email": null,
"hireable": null,
"bio": null,
"twitter_username": null,
"public_repos": 3,
"public_gists": 14,
"followers": 9,
"following": 13,
"created_at": "2012-10-14T10:22:40Z",
"updated_at": "2021-04-15T09:57:13Z"
};

That’s the sample response from githubs api, you can use it from: https://api.github.com/users/davit

Now about functionality, Nock will match data from from the creater file (Above) with actual data from API response.

Enjoy, Subscribe And Clap!

Peace ✌️

--

--

Davit Danelia

SDET at EPAM systems / QA Lead at Sharemac / GeoSTQB Inovations boar member