Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
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.
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');
Sinon is a testing utility that focuses on spies, stubs, and mocks. While it does not specialize in HTTP request mocking like nock, it can be used in conjunction with other libraries to achieve similar results.
This package is specifically designed to work with axios, a popular HTTP client. It allows for mocking axios requests, similar to how nock mocks Node.js HTTP requests, but is limited to axios instances.
Fetch-mock is designed to mock HTTP requests made using the fetch API. It offers similar functionality to nock but is tailored for the global fetch method rather than Node.js HTTP modules.
Jest-mock-axios is a mock for axios library that is specifically built to work with Jest testing framework. It provides a simple and easy-to-use API for mocking axios requests and responses.
Supertest is a library that allows you to test HTTP servers by making requests to them. It is often used in conjunction with a real server instance, unlike nock which mocks the HTTP requests at a lower level.
Nock is an HTTP mocking and expectations library 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('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 200, and the body will contain a user representation in JSON.
Then the test can call the module, and the module will do the HTTP requests.
When you setup an interceptor for an URL and that interceptor is used, it is removed from the interceptor list. This means that if you can intercept 2 or more calls to the same URL and return different things on each of them. It also means that you must setup one interceptor for each request you are going to have, otherwise nock will throw an error because that URL was not present in the interceptor list.
You can specify the request body to be matched as the second argument to the get
, post
, put
or delete
specifications like this:
var scope = nock('http://myapp.iriscouch.com')
.post('/users', {username: 'pgte', email: 'pedro.teixeira@gmail.com'})
.reply(201, {ok: true, id: "123ABC", rev: "946B7D1C"});
The request body can be a string or a JSON object.
You can specify the return status code for a path on the first argument of reply like this:
var scope = nock('http://myapp.iriscouch.com')
.get('/users/1')
.reply(404);
You can also specify the reply body as a string:
var scope = nock('http://www.google.com')
.get('/')
.reply(200, "Hello from Google!");
or as a JSON-encoded object:
var scope = nock('http://myapp.iriscouch.com')
.get('/')
.reply(200, {username: 'pgte', email: 'pedro.teixeira@gmail.com', _id: "4324243fsd"});
or even as a file:
var scope = nock('http://myapp.iriscouch.com')
.get('/')
.replyWithFile(200, __dirname + '/replies/user.json');
You can specify the reply headers like this:
var scope = nock('http://www.headdy.com')
.get('/')
.reply(200, "Hello World!", {'X-My-Headers': 'My Header value'});
You can also specify default reply headers for all responses like this:
var scope = nock('http://www.headdy.com')
.defaultReplyHeaders({'X-Powered-By': 'Rails', 'Content-Type': 'application/json'})
.get('/')
.reply(200, 'The default headers should come too');
Nock supports get, post, put and delete HTTP verbs.
By default nock assumes HTTP. If you need to use HTTPS you can specify the https://
prefix like this:
var scope = nock('https://secure.my.server.com')
// ...
You can chain behaviour like this:
var scope = 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'});
You can also filter the URLs based on a function.
This can be useful, for instance, if you have random or time-dependent data in your URL.
You can use a regexp for replacement, just like String.prototype.replace:
var scope = nock('http://api.myservice.com')
.filteringPath(/password=[^&]*/g, 'password=XXX')
.get('/users/1?password=XXX')
.reply(200, 'user');
Or you can use a function:
var scope = nock('http://api.myservice.com')
.filteringPath(function(path) {
return '/ABC';
})
.get('/ABC')
.reply(200, 'user');
You can also filter the request body based on a function.
This can be useful, for instance, if you have random or time-dependent data in your URL.
You can use a regexp for replacement, just like String.prototype.replace:
var scope = nock('http://api.myservice.com')
.filteringRequestBody(/password=[^&]*/g, 'password=XXX')
.post('/users/1', 'data=ABC&password=XXX')
.reply(201, 'OK');
Or you can use a function:
var scope = nock('http://api.myservice.com')
.filteringRequestBody(function(path) {
return 'ABC';
})
.post('/', 'ABC')
.reply(201, 'OK');
If you need to match requests only if certain request headers match, you can.
var scope = nock('http://api.myservice.com')
.matchHeader('accept', 'application/json')
.get('/')
.reply(200, {data: "hello world"})
If you need some request on the same host name to be mocked and some others to really go through the HTTP stack, you can use the allowUnmocked
option like this:
options = {allowUnmocked: true};
var scope = nock('http://my.existing.service.com', options)
.get('/my/url')
.reply(200, 'OK!');
GET /my/url => goes through nock
GET /other/url => actually makes request to the server
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.
}, 5000);
You can also call isDone()
, which will return a boolean saying if all the expectations are met or not (instead of throwing an exception);
You can cleanup all the prepared mocks (could be useful to cleanup some state after a failed test) like this:
nock.cleanAll();
Nock can log matches if you pass in a log function like this:
var google = nock('http://google.com')
.log(console.log)
...
You can restore the HTTP interceptor to the normal unmocked behaviour by calling:
nock.restore();
This is a cool feature:
Guessing what the HTTP calls are is a mess, specially if you are introducing nock on your already-coded tests.
For these cases where you want to mock an existing live system you can record and playback the HTTP calls like this:
nock.recorder.rec();
// Some HTTP calls happen and the nock code necessary to mock
// those calls will be outputted to console
If you just want to capture the generated code into a var as an array you can use:
nock.recorder.rec(true); // :no_output = true
// ... some HTTP calls
var nockCalls = nock.recorder.play();
The nockCalls
var will contain an array of strings representing the generated code you need.
Copy and paste that code into your tests, customize at will, and you're done!
(Remember that you should do this one test at a time).
Nock works by overriding Node's http.request
function. Also, it overrides http.ClientRequest
too to cover for modules that use it directly.
(The MIT License)
Copyright (c) 2011 Pedro Teixeira. http://about.me/pedroteixeira
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
HTTP server mocking and expectations library for Node.js
The npm package nock receives a total of 2,210,717 weekly downloads. As such, nock popularity was classified as popular.
We found that nock demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
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.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.