Nock は Node.js 向けの HTTP サーバーモック&エクスペクテーションライブラリで、http.request 経由の発信ネットワーク呼び出しをインターセプトします。
基本的なモック定義
const nock = require('nock');
// GET エンドポイントをモック化
const scope = nock('https://api.example.com')
.get('/users/1')
.reply(200, {
id: 1,
name: 'Alice Cooper'
});
// モック化されていないリクエストを実際のネットワークへ通過させる
const unmockedScope = nock('https://api.example.com', {
allowUnmocked: true
});
リクエストフィルタリングとクエリ一致
クエリパラメータの一致指定
nock('https://api.example.com')
.get('/search')
.query({ q: 'cheese', page: '1' })
.reply(200, { results: [] });
パスフィルタリング(動的トークンのマスク)
マッチング前に動的なトークンやタイムスタンプを取り除きます:
nock('https://api.example.com')
.filteringPath(/[&?]token=[^&]*/g, '')
.get('/user')
.reply(200, { authorized: true });
// "/user?token=xyz123" を "/user" としてインターセプト
POST リクエストとヘッダーのモック
nock('https://api.example.com')
.matchHeader('authorization', 'Bearer token_123')
.post('/checkout', { items: [1, 2] })
.reply(201, { status: 'created' }, {
'X-Custom-Header': 'MockValue'
});
アサーションとクリーンアップ
// 宣言されたすべてのインターセプターが呼び出されたか検証
scope.isDone(); // => true / false
// 有効なすべてのインターセプターを消去
nock.cleanAll();
// Node.js 本来の HTTP 動作を復元
nock.restore();