Học Playwright tiếng Việt, Cộng đồng Playwright cho người Việt

Khóa học

[Vọc Playwright] Mock API

https://playwright.dev/docs/mock

Introduction

  • Plawright cung cấp mock để thay đổi request, response của request.
  • Bạn có thể mock từng request, hoặc sử dụng HAR files để mock nhiều network request cùng lúc.

Mock API requests

  • Để mock API request thì dùng hàm route.fulfill(data)
test("mocks a fruit and doesn't call api", async ({ page }) => {
  // Mock the api call before navigating
  await page.route('*/**/api/v1/fruits', async route => {
    const json = [{ name: 'Strawberry', id: 21 }];
    await route.fulfill({ json });
  });
  // Go to the page
  await page.goto('https://demo.playwright.dev/api-mocking');

  // Assert that the Strawberry fruit is visible
  await expect(page.getByText('Strawberry')).toBeVisible();
});
  • Đối với các mock request, tại report bạn sẽ thấy label fulfilled

Thay đổi API response

  • Thi thoảng, bạn cũng cần thay đổi API response để test.
  • Để modify thì làm tương tự như mock. Khác cái là dùng hàm route.fetch() để lấy ra response trước, modify response rồi mock lại.
test('gets the json from api and adds a new fruit', async ({ page }) => {
  // Get the response and add to it
  await page.route('*/**/api/v1/fruits', async route => {
    const response = await route.fetch();
    const json = await response.json();
    json.push({ name: 'Loquat', id: 100 });
    // Fulfill using the original response, while patching the response body
    // with the given JSON object.
    await route.fulfill({ response, json });
  });

  // Go to the page
  await page.goto('https://demo.playwright.dev/api-mocking');

  // Assert that the new fruit is visible
  await expect(page.getByText('Loquat', { exact: true })).toBeVisible();
});
  • Trong trace, bạn sẽ thấy có cả request được gọi và cả request được fulfilled.

Mocking với HAR files

  • HAR file là một file chứa thông tin các request.
  • Bạn có thể dùng HAR file để mock lại các network requests.
  • Để mock sử dụng HAR file, bạn cần:
  1. Record HAR file.
  2. Commit HAR file cùng với test.
  3. Route request sử dụng file HAR trong test.

Record HAR file

  • Sử dụng method page.routeFromHAR() hoặc browserContext.routeFromHAR().
  • Method này gồm có 2 tham số:
    • Đường dẫn lưu file HAR
    • Object optional chứa:
      • URL pattern sẽ record vào HAR file.
      • Thuộc tính update: bật/tắt việc tạo mới hoặc update HAR file
test('records or updates the HAR file', async ({ page }) => {
  // Get the response from the HAR file
  await page.routeFromHAR('./hars/fruit.har', {
    url: '*/**/api/v1/fruits',
    update: true,
  });

  // Go to the page
  await page.goto('https://demo.playwright.dev/api-mocking');

  // Assert that the fruit is visible
  await expect(page.getByText('Strawberry')).toBeVisible();
});

Record sử dụng CLI

  • Thêm option --save-har vào là được
  • Nếu chỉ muốn record các request theo pattern thì dùng --save-har-glob:
# Save API requests from example.com as "example.har" archive.
npx playwright open --save-har=example.har --save-har-glob="**/api/**" https://example.com

Thay đổi HAR file

  • Sửa file hashed.txt trong folder hars

Replaying từ HAR file

  • Làm giống hệt mục record, thay giá trị update về false là được.

Trả lời