Snelle referentie

Nock HTTP-Mocking Spiekbriefje

Beknopte referentiegids voor Nock: HTTP-server mocking- en expectation-bibliotheek voor Node.js, URL-filtering, query-matching en mockantwoorden.

· Gepubliceerd

Nock is een HTTP-server mocking- en expectation-bibliotheek voor Node.js die uitgaande netwerkaanroepen via http.request onderschept.

Basis Mocking

const nock = require('nock');

// Een GET-endpoint mocken
const scope = nock('https://api.example.com')
  .get('/users/1')
  .reply(200, {
    id: 1,
    name: 'Alice Cooper'
  });

// Niet-gemockte verzoeken doorlaten naar het echte netwerk
const unmockedScope = nock('https://api.example.com', {
  allowUnmocked: true
});

Request-filtering & Query-matching

Queryparameters Matchen

nock('https://api.example.com')
  .get('/search')
  .query({ q: 'cheese', page: '1' })
  .reply(200, { results: [] });

Paden Filteren (Dynamische Tokens Maskeren)

Strip dynamische tokens of tijdstempels vóór het matchen:

nock('https://api.example.com')
  .filteringPath(/[&?]token=[^&]*/g, '')
  .get('/user')
  .reply(200, { authorized: true });

// Onderschept "/user?token=xyz123" als "/user"

POST-verzoeken & Headers Mocken

nock('https://api.example.com')
  .matchHeader('authorization', 'Bearer token_123')
  .post('/checkout', { items: [1, 2] })
  .reply(201, { status: 'created' }, {
    'X-Custom-Header': 'MockValue'
  });

Assertions & Opschonen

// Controleer of alle gedeclareerde interceptors zijn aangeroepen
scope.isDone(); // => true / false

// Alle actieve interceptors opschonen
nock.cleanAll();

// Oorspronkelijke HTTP-gedrag van Node.js herstellen
nock.restore();

Referenties

Verwante onderwerpen