Nock is an HTTP server mocking and expectation library for Node.js, intercepting outgoing network calls via http.request.
Basic Mocking
const nock = require('nock');
// Mock a GET endpoint
const scope = nock('https://api.example.com')
.get('/users/1')
.reply(200, {
id: 1,
name: 'Alice Cooper'
});
// Allow unmocked requests to pass through to real network
const unmockedScope = nock('https://api.example.com', {
allowUnmocked: true
});
Request Filtering & Query Matching
Matching Query Parameters
nock('https://api.example.com')
.get('/search')
.query({ q: 'cheese', page: '1' })
.reply(200, { results: [] });
Filtering Paths (Masking Dynamic Tokens)
Strip dynamic tokens or timestamps before matching:
nock('https://api.example.com')
.filteringPath(/[&?]token=[^&]*/g, '')
.get('/user')
.reply(200, { authorized: true });
// Intercepts '/user?token=xyz123' as '/user'
Mocking POST Requests & Headers
nock('https://api.example.com')
.matchHeader('authorization', 'Bearer token_123')
.post('/checkout', { items: [1, 2] })
.reply(201, { status: 'created' }, {
'X-Custom-Header': 'MockValue'
});
Assertions & Cleanup
// Verify that all declared interceptors were invoked
scope.isDone(); // => true / false
// Clean all active interceptors
nock.cleanAll();
// Restore original Node.js HTTP behavior
nock.restore();