웹 애플리케이션의 자동화된 테스트에는 종종 외부 API와의 상호 작용이 필요합니다. 하지만 실제 API 응답에 의존하면 네트워크 문제나 서버 다운타임과 같이 통제할 수 없는 변수가 발생할 수 있습니다. 바로 이 점이 API 모킹이 필요한 이유입니다. 모킹을 사용하면 API 응답을 시뮬레이션하여 테스트를 더 안정적이고 빠르게 수행할 수 있습니다. 이 글에서는 TypeScript로 Playwright를 사용하여 API를 모의하는 방법을 살펴보겠습니다.
Playwright에서 API 모의하기
Playwright는 route
메서드를 사용하여 네트워크 요청을 가로채고 응답을 모의하는 방법을 제공합니다. API 응답을 모의하는 예제를 살펴보겠습니다.
단계별 가이드
1. 필요한 모듈 가져오기 + 기본 테스트 생성
TypeScript
import { test, expect, chromium } from '@playwright/test';
test('Mock User Profile API', async ({ page }) => {
await page.goto('https://example.com/profile');
// 여기서 모의 테스트 수행
});
2. 요청 차단 및 모의 설정
TypeScript
test('Mock User Profile API', async ({ page }) => {
// 시나리오 1: 데이터 검색 성공
await page.route('https://api.example.com/user/profile', route => {
const mockResponse = {
status: 200,
contentType: 'application/json',
body: JSON.stringify({
name: 'John Doe',
email: '[email protected]',
age: 30
})
};
route.fulfill(mockResponse);
});
await page.goto('https://example.com/profile');
const userName = await page.textContent('#name'); // Assuming the name is rendered in an element with id 'name'
const userEmail = await page.textContent('#email'); // Assuming the email is rendered in an element with id 'email'
const userAge = await page.textContent('#age'); // Assuming the age is rendered in an element with id 'age'
expect(userName).toBe('John Doe');
expect(userEmail).toBe('[email protected]');
expect(userAge).toBe('30');
});
3. 시나리오 추가하기
TypeScript
test('Mock User Profile API - Empty Profile', async ({ page }) => {
// 시나리오 2: 빈 사용자 프로필
await page.route('https://api.example.com/user/profile', route => {
const mockResponse = {
status: 200,
contentType: 'application/json',
body: JSON.stringify({})
};
route.fulfill(mockResponse);
});
await page.goto('https://example.com/profile');
const userName = await page.textContent('#name');
const userEmail = await page.textContent('#email');
const userAge = await page.textContent('#age');
expect(userName).toBe('');
expect(userEmail).toBe('');
expect(userAge).toBe('');
});
test('Mock User Profile API - Server Error', async ({ page }) => {
// 시나리오 3: 서버 오류
await page.route('https://api.example.com/user/profile', route => {
const mockResponse = {
status: 500,
contentType: 'application/json',
body: JSON.stringify({ error: 'Internal Server Error' })
};
route.fulfill(mockResponse);
});
await page.goto('https://example.com/profile');
const errorMessage = await page.textContent('#error'); // Assuming the error message is rendered in an element with id 'error'
expect(errorMessage).toBe('Internal Server Error');
});
테스트 실행하기
npx playwright test
고급 모킹 기법
플레이라이트에서는 조건부 응답이나 지연 등 보다 고급 모킹 기법을 사용할 수 있습니다. 다음은 조건부 모의의 예시입니다:
TypeScript
test('Conditional Mocking', async ({ page }) => {
await page.route('https://api.example.com/user/profile', route => {
if (route.request().method() === 'POST') {
route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ message: 'Profile created' })
});
} else {
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
name: 'John Doe',
email: '[email protected]',
age: 30
})
});
}
});
await page.goto('https://example.com/profile');
// 추가 테스트 로직은 여기
});
네트워크 지연을 시뮬레이션하기 위해 지연을 도입할 수도 있습니다:
TypeScript
test('Mock with Delay', async ({ page }) => {
await page.route('https://api.example.com/user/profile', async route => {
await new Promise(res => setTimeout(res, 2000)); // Delay for 2 seconds
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
name: 'John Doe',
email: '[email protected]',
age: 30
})
});
});
await page.goto('https://example.com/profile');
// 추가 테스트 로직은 여기
});
결론
Mocking APIs in Playwright with TypeScript는 테스트의 신뢰성과 속도를 향상시키는 강력한 기술입니다. 네트워크 요청을 가로채고 사용자 정의 응답을 제공함으로써 다양한 시나리오를 시뮬레이션하고 애플리케이션이 다양한 조건에서 예상대로 동작하는지 확보할 수 있습니다.
이 가이드가 Playwright 테스트에서 API 노킹 시작에 도움이 되길 바랍니다. 행복한 테스트 하세요!
Source:
https://dzone.com/articles/effortless-api-mocking-with-playwright