nock – Mocking HTTP requests in NodeJs

When writing unit tests for a NodeJs app you sometimes want to mock out HTTP requests. Nock (https://github.com/pgte/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 http://www.example.com/api/product/15, expecting some basic product data as a result:


nock('http://example.com')
.get('/api/product/15')
.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 (https://github.com/pgte/nock), 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.: http://www.example.com/api/*)
* 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 :)

~m

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>