Nock è una libreria di mocking server HTTP ed expectation per Node.js che intercetta le chiamate di rete in uscita tramite http.request.
Mocking di Base
const nock = require('nock');
// Simula un endpoint GET
const scope = nock('https://api.example.com')
.get('/users/1')
.reply(200, {
id: 1,
name: 'Alice Cooper'
});
// Consenti alle richieste non simulate di raggiungere la rete reale
const unmockedScope = nock('https://api.example.com', {
allowUnmocked: true
});
Filtraggio Richieste & Query Matching
Matching dei Parametri Query
nock('https://api.example.com')
.get('/search')
.query({ q: 'cheese', page: '1' })
.reply(200, { results: [] });
Filtraggio dei Percorsi (Mascherare Token Dinamici)
Rimuovi token dinamici o timestamp prima della verifica:
nock('https://api.example.com')
.filteringPath(/[&?]token=[^&]*/g, '')
.get('/user')
.reply(200, { authorized: true });
// Intercetta "/user?token=xyz123" come "/user"
Simulare Richieste POST e Header
nock('https://api.example.com')
.matchHeader('authorization', 'Bearer token_123')
.post('/checkout', { items: [1, 2] })
.reply(201, { status: 'created' }, {
'X-Custom-Header': 'MockValue'
});
Asserzioni & Pulizia
// Verifica che tutti gli intercettori dichiarati siano stati invocati
scope.isDone(); // => true / false
// Pulisci tutti gli intercettori attivi
nock.cleanAll();
// Ripristina il comportamento HTTP originale di Node.js
nock.restore();