以下代碼將攔截所有?*/**/api/v1/fruits?接口調用,并返回自定義響應,測試執行的時候,不會向 API 發出任何請求。

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();
});

該測試將請求轉到模擬路由 URL 上,并斷言頁面上存在模擬數據。

運行 npx playwright test --ui

執行測試用例,并且查看 trace viewer

從上圖看到接口請求數據已經被攔截。

修改 API 響應

有時需要發出 API 請求,但需要修改響應數據來測試。在這種情況下,可以執行請求并修改返回的接口數據。

例如:一些 ui 權限控制展示等

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();
});

運行測試,我們可以看到 network 中的請求包含了 2 次,一次來源于 Page#1

通過檢查響應,可以看到 mock 中添加的新水果已顯示在列表中。

使用 HAR 文件進行 Mock

HAR 文件是一個 HTTP 存檔文件,其中包含加載頁面時發出的所有網絡請求的記錄。它包含有關請求和響應標頭、Cookie、內容、時間等的信息。我們可以使用 HAR 文件在測試中模擬網絡請求。并將測試執行持續集成(CI),需要 3 個步驟:

  1. 錄制 HAR 文件。
  2. 將 HAR 文件與測試一起提交。
  3. 在測試中使用保存的 HAR 文件路由請求。

錄制一個 Har 文件

為了錄制 HAR 文件,我們使用 page.routeFromHAR() 或 browserContext.routeFromHAR() 方法。此方法接受 HAR 文件的路徑和可選一個可選對象 options。對象可以包含 url 用于指定 glob 模式匹配的請求才會錄制到 HAR 文件中。如果未指定,則將所有請求都錄制到 HAR 文件中。

test('records or updates the HAR file', async ({ page }) => {
// Get the response from the HAR file
await page.routeFromHAR('./hars/fruits.har', {
url: '*/**/api/v1/fruits',
update: true,
});

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

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

執行測試用例后將會生成一個 HAR 文件。

HAR 文件就是一個 json 文件,保存了 mock 請求接口信息,接口響應結果保存到 bin 文件中。

修改 HAR 文件

一旦錄制完成了一個 HAR 文件,我們就可以通過在?hars?文件夾下,找到哈希?.bin?文件并編輯, 將修改后的文件提交到源代碼管理中。當使用?update:true?運行此測試時,就會使用 API 請求更新 HAR 文件。

[
{
"name": "Playwright",
"id": 100
},
// ... other fruits
]

使用錄制的 HAR 文件進行 mock 測試

現在,我們已經記錄了 HAR 文件并修改了 mock 數據,只需update?改為 false 或者刪除即可。這將針對 HAR 文件運行測試,而不是真實的 API。

test('gets the json from HAR and checks the new fruit has been added', async ({ page }) => {
// Replay API requests from HAR.
// Either use a matching response from the HAR,
// or abort the request if nothing matches.
await page.routeFromHAR('./hars/fruits.har', {
url: '*/**/api/v1/fruits',
update: false,
});

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

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

查看 trace viewer,我們可以看到路由是從 HAR 文件實現的,并且未調用 API。

檢查網絡響應,可以看到新數據已添加到 JSON 中,這是通過手動更新 hars 文件夾中的哈希.bin文件來完成的。

HAR 需要嚴格匹配 URL 和 HTTP 方法。對于 POST 請求,它還需要嚴格匹配 POST 有效負載。

如果給定的 HAR 文件名以 .zip 結尾,則會將 HAR 文件和錄制的網絡 json 打包為 zip。我們可以解壓 zip 文件,手動編輯數據。

使用 CLI 錄制 HAR 文件

Playwright 還支持使用 CLI 錄制 HAR。

使用 Playwright CLI 打開瀏覽器并傳遞?--save-har?選項以生成 HAR 文件。(可選參數)使用?--save-har-glob?僅保存您感興趣的請求,例如 API 接口。如果 har 文件名以 .zip 結尾,則會將錄制的所有文件都壓縮到一個 zip 中。

npx playwright open --save-har=example.har --save-har-glob="**/api/**" https://example.com

參考

文章轉自微信公眾號@JS酷

上一篇:

使用 Django 和 Django REST 框架構建 RESTful API:實現 CRUD 操作

下一篇:

JSX AS DSL? 寫個 Mock API 服務器看看
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費