Socket
Socket
Sign inDemoInstall

nock

Package Overview
Dependencies
0
Maintainers
1
Versions
422
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    nock

HTTP Server mocking for Node.js


Version published
Weekly downloads
2.9M
increased by2.84%
Maintainers
1
Install size
14.3 kB
Created
Weekly downloads
 

Package description

What is nock?

The nock npm package is a powerful HTTP server mocking and expectations library for Node.js. It allows developers to test modules that perform HTTP requests in isolation. By intercepting outgoing HTTP requests and providing mock responses, nock enables a more controlled and predictable testing environment.

What are nock's main functionalities?

Intercepting HTTP Requests

This feature allows you to intercept an HTTP GET request to a specified URL and provide a custom response.

const nock = require('nock');
const http = require('http');

nock('http://example.com')
  .get('/resource')
  .reply(200, 'domain matched');

http.get('http://example.com/resource', (res) => {
  // This will receive the mocked response
});

Specifying Response Status and Body

With nock, you can specify the HTTP response status and body for a mocked endpoint, allowing you to simulate different server responses.

const nock = require('nock');

nock('http://example.com')
  .post('/login')
  .reply(401, { error: 'Unauthorized' });

Dynamic Response Functions

Nock can use functions to dynamically generate responses based on the incoming request data.

const nock = require('nock');

nock('http://example.com')
  .get('/data')
  .reply(200, (uri, requestBody) => {
    return { data: 'Dynamic response based on request' };
  });

Recording and Playback

Nock can record HTTP requests and responses and then play them back, which is useful for creating fixtures or reproducing issues.

const nock = require('nock');

nock.recorder.rec();
// Perform HTTP requests
// Nock will record the requests and responses
// Stop recording
nock.recorder.play();

Specifying Request Headers

This feature allows you to specify expected request headers and mock responses accordingly, which is useful for testing authentication and other header-dependent functionality.

const nock = require('nock');

nock('http://example.com', {
  reqheaders: {
    'authorization': 'Bearer token',
    'content-type': 'application/json'
  }
})
.get('/protected/resource')
.reply(200, 'Authenticated content');

Other packages similar to nock

Readme

Source

Nock

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.

Install

$ npm install nock

Use

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

var nock = require('nock');

var couchdb = nock('http://myapp.iriscouch.com')
                .get('/users/1')
                .reply(200, {_id: "123ABC", _rev: "946B7D1C", username: 'pgte', email: 'pedro.teixeira@gmail.com'});

This setup says that we will intercept every HTTP call to http://myapp.iriscouch.com.

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('http://myapp.iriscouch.com') .get('/users/1') .reply(404);

You can also specify the reply body as a string:

var couchdb = nock('http://www.google.com') .get('/') .reply(200, "Hello from Google!");

as a JSON-encoded object:

var couchdb = nock('http://myapp.iriscouch.com') .get('/') .reply(200, {username: 'pgte', email: 'pedro.teixeira@gmail.com', _id: "4324243fsd"});

or even as a file:

var couchdb = nock('http://myapp.iriscouch.com') .get('/') .replyWithFile(200, __dirname + '/replies/user.json');

Chaining

You can chain behaviour like this:

var couchdb = nock('http://myapp.iriscouch.com')
                .get('/users/1')
                .reply(404)
                .post('/users', {username: 'pgte', email: 'pedro.teixeira@gmail.com'})
                .reply(201, {ok: true, id: "123ABC", rev: "946B7D1C"})
                .get('/users/123ABC')
                .reply(200, {_id: "123ABC", _rev: "946B7D1C", username: 'pgte', email: 'pedro.teixeira@gmail.com'});

Expectations

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.

Example:

var google = nock('http://google.com')
                .get('/')
                .reply(200, 'Hello from Google!');

// do some stuff

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

How does it work?

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

FAQs

Last updated on 22 Sep 2011

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc