nock – Mocking HTTP requests in NodeJs

When writing unit tests for a NodeJs app you sometimes want to mock out HTTP requests. Nock ( is a really nice lib for doing just that.

It’s installed in the usual way with npm:

npm install nock

and can be included in a test like this:

var nock = require('nock');

Now, let’s say, you want to mock out an API call to, expecting some basic product data as a result:

.reply(200, {
    data: {
        id: '15',
        name: 'Flamethrower 5000',
        price: '5000'

You can put this, for example, in the ‘beforeEach’-block of a mocha or jasmine test.

The basic example above will get you pretty far, but as you can read in the excellent docs (, you can do all kinds of fancy stuff with nock such as:

* get / post / put / delete
* custom headers for requests and responses
* http and https
* response repetition
* chaining
* filtering & matching (e.g.:*)
* logging
* recording (this is really cool for complex responses, you can record and then play back http requests and responses)
* … much much more!

Pretty much everything you’ll ever use in your applications, you will be able to mock out with a clean and simple syntax. Really cool.

Have fun nocking :)