0

[Playwright Interview question #12]: Network interception và mocking API response được thực hiện như thế nào?

Câu hỏi phỏng vấn #12: Network interception và mocking API response được thực hiện như thế nào?

Trả lời mẫu:

Playwright cung cấp powerful network interception capabilities:

1. Mock API response:

await page.route('**/api/users', async route => {
  await route.fulfill({
    status: 200,
    contentType: 'application/json',
    body: JSON.stringify({ users: ['John', 'Jane'] })
  });
});

2. Modify response:

await page.route('**/api/data', async route => {
  const response = await route.fetch();
  const json = await response.json();
  json.modified = true;
  
  await route.fulfill({
    response,
    json
  });
});

3. Block resources:

// Block images và CSS
await page.route(/(\.png$)|(\.jpg$)|(\.css$)/, route => route.abort());

4. Network conditions:

// Simulate slow network
await page.route('**/*', async route => {
  await page.waitForTimeout(1000); // Delay 1s
  await route.continue();
});

5. HAR replay:

// Record HAR
await page.routeFromHAR('network.har', {
  url: '**/api/**',
  update: true
});

// Replay from HAR
await page.routeFromHAR('network.har');

💡 Tips:

  • Use route patterns wisely với glob hoặc regex
  • Mock external APIs để test nhanh và stable hơn
  • HAR files perfect cho offline testing
  • Combine với assertions: expect(response.status()).toBe(200)

Lời Kết

Playwright đang trở thành một trong những automation frameworks phổ biến nhất cho web testing. Thông qua series này, hy vọng bạn sẽ:

  • Nắm vững kiến thức từ cơ bản đến nâng cao
  • Tự tin trong các buổi phỏng vấn
  • Áp dụng hiệu quả vào dự án thực tế
  • Trở thành một phần của cộng đồng Playwright Việt Nam năng động

📚 Bắt đầu hành trình của bạn với: Bài 1: Playwright vs Selenium

💬 Có câu hỏi? Tham gia group Facebook của chúng mình!

Theo dõi series để không bỏ lỡ bài viết mới!


All Rights Reserved

Viblo
Let's register a Viblo Account to get more interesting posts.