5.2 Route, HAR mocking
page.route 또는 context.route로 request를 abort, fulfill, continue할 수 있습니다.
await page.route('**/api/summary', async route => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ total: 3 }),
});
});
실제 response 일부를 바꾸려면 upstream을 fetch합니다.
await page.route('**/api/profile', async route => {
const response = await route.fetch();
const body = await response.json();
await route.fulfill({ response, json: { ...body, role: 'admin' } });
});
Mock은 frontend edge case를 빠르고 결정적으로 만들지만 backend contract가 틀려도 test가 통과할 수 있습니다. 실제 integration test와 mock test의 목적을 구분합니다.
HAR replay는 여러 request를 파일로 기록, 재생합니다.
await page.routeFromHAR('fixtures/api.har', {
url: '**/api/**',
update: false,
});
HAR에는 header, query, response body와 credential이 포함될 수 있습니다. Sanitize와 보관 정책을 적용하고 제품 API 변경 때 fixture를 갱신합니다.
참고: Mock APIs
Mock 수준 비교
// 완전 대체
await page.route('**/api/summary', route => route.fulfill({
json: { source: 'mock', total: 42 },
}));
// 원본을 받아 일부 수정
await page.route('**/api/summary', async route => {
const response = await route.fetch();
const json = await response.json();
await route.fulfill({ response, json: { ...json, total: 99 } });
});
공식 example도 complete mock, response modification, HAR replay를 분리합니다. Test title에 어느 경계를 쓰는지 드러냅니다.
Error matrix
- 401/403 authorization
- 404 missing resource
- 409 conflict
- 429 rate limit
- 500/503 server failure
- Connection abort
- Malformed JSON
- Slow response
모든 case를 E2E에 넣지 않고 사용자 recovery가 달라지는 대표 상태를 선택합니다.
실습
- Summary를 42로 완전 mock합니다.
- Real response를 가져와 total만 99로 수정합니다.
- 503 뒤 retry button을 눌러 recovery를 확인합니다.
- HAR에 secret이 없는지 검사합니다.