Skip to content


Subversion checkout URL

You can clone with
Download ZIP
HTTP mocking and expectations library
Fetching latest commit...
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.


HTTP Server mocking for Node.js

Nock can be used to test modules that perform HTTP requests in isolation.

For instance, if a module performs HTTP requests to a CouchDB server or makes HTTP requests to the Amazon API, you can test that module in isolation.


$ npm install nock


On your test, you can setup your mocking object like this:

var nock = require('nock');

var couchdb = nock('')
                .reply(200, {_id: "123ABC", _rev: "946B7D1C", username: 'pgte', email: ''});

This setup says that we will intercept every HTTP call to

It will intercept an HTTP GET request to '/users/1' and reply with a status 404.

Then the test can call the module, and the module will do the HTTP requests.

Specifying replies

You can specify the return status code for a path on the first argument of reply like this:

var couchdb = nock('') .get('/users/1') .reply(404);

You can also specify the reply body as a string:

var couchdb = nock('') .get('/') .reply(200, "Hello from Google!");

as a JSON-encoded object:

var couchdb = nock('') .get('/') .reply(200, {username: 'pgte', email: '', _id: "4324243fsd"});

or even as a file:

var couchdb = nock('') .get('/') .replyWithFile(200, __dirname + '/replies/user.json');


You can chain behaviour like this:

var couchdb = nock('')
                .post('/users', {username: 'pgte', email: ''})
                .reply(201, {ok: true, id: "123ABC", rev: "946B7D1C"})
                .reply(200, {_id: "123ABC", _rev: "946B7D1C", username: 'pgte', email: ''});


Every time an HTTP request is performed for a scope that is mocked, Nock expects to find a handler for it. If it doesn't, it will throw an error.

Calls to nock() return a scope which you can assert by calling scope.done(). This will assert that all specified calls on that scope were performed.


var google = nock('')
                .reply(200, 'Hello from Google!');

// do some stuff

setTimeout(function() {
  google.done(); // will throw an assertion error if meanwhile a "GET" was not performed.

How does it work?

Nock works by overriding Node's http.request function.

Something went wrong with that request. Please try again.