Nock은 http.request를 통해 나가는 네트워크 호출을 가로채는 Node.js용 HTTP 서버 모킹 및 검증 라이브러리입니다.
기본 모킹
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();