Skip to main content

發行說明

版本 1.55

新的 API

  • 新屬性 testStepInfo.titlePath 回傳從測試檔案開始的完整標題路徑,包含測試和步驟標題。

錄製測試

  • 自動 toBeVisible() 斷言:Codegen 現在可以為常見的 UI 互動產生自動 toBeVisible() 斷言。此功能可以在 Codegen 設定 UI 中啟用。

重大變更

  • ⚠️ 已移除對 Chromium 擴充功能 manifest v2 的支援。

其他

  • 新增對 Debian 13 "Trixie" 的支援。

瀏覽器版本

  • Chromium 140.0.7339.16
  • Mozilla Firefox 141.0
  • WebKit 26.0

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 139
  • Microsoft Edge 139

版本 1.54

重點

  • browserContext.cookies()browserContext.addCookies() 中新增 cookie 屬性 partitionKey。此屬性允許儲存和還原分割的 cookies。請參閱 CHIPS MDN 文章 以取得更多資訊。請注意,瀏覽器對 cookie 分割有不同的支援和預設值。

  • 新選項 noSnippets 用於在 html 報告中停用程式碼片段。

    import { defineConfig } from '@playwright/test';

    export default defineConfig({
    reporter: [['html', { noSnippets: true }]]
    });
  • 測試註釋中的新屬性 location,例如在 testResult.annotationstestInfo.annotations 中。它顯示像 test.skiptest.fixme 這樣的註釋是在何處新增的。

命令列

  • 在多個指令中新增選項 --user-data-dir。您可以指定相同的使用者資料目錄來重複使用瀏覽狀態,例如驗證,在不同的會話之間。

    npx playwright codegen --user-data-dir=./user-data
  • 選項 -gv 已從 npx playwright test 指令中移除。請改用 --grep-invert

  • npx playwright open 不再開啟測試錄製器。請改用 npx playwright codegen

其他

  • 已移除對 Node.js 16 的支援。
  • 已棄用對 Node.js 18 的支援,將來會移除。

瀏覽器版本

  • Chromium 139.0.7258.5
  • Mozilla Firefox 140.0.2
  • WebKit 26.0

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 140
  • Microsoft Edge 140

版本 1.53

追蹤檢視器和 HTML 報告器更新

  • 追蹤檢視器和 HTML 報告器中的新步驟:新的追蹤檢視器步驟

  • 'html' 報告器中的新選項用於設定特定測試執行的標題:

    import { defineConfig } from '@playwright/test';

    export default defineConfig({
    reporter: [['html', { title: 'Custom test run #1028' }]]
    });

其他

  • testInfo.snapshotPath() 中的新選項 kind 控制使用哪個快照路徑範本。

  • 新方法 locator.describe() 用於描述定位器,在追蹤檢視器和報告中使用。

    const button = page.getByTestId('btn-sub').describe('Subscribe button');
    await button.click();
  • npx playwright install --list 現在會列出所有已安裝的瀏覽器、版本和位置。

瀏覽器版本

  • Chromium 138.0.7204.4
  • Mozilla Firefox 139.0
  • WebKit 18.5

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 137
  • Microsoft Edge 137

版本 1.52

重點

  • 新方法 expect(locator).toContainClass() 用於人體工學地斷言元素上的個別類別名稱。

    await expect(page.getByRole('listitem', { name: 'Ship v1.52' })).toContainClass('done');
  • Aria Snapshots 獲得兩個新屬性:/children 用於嚴格匹配和 /url 用於連結。

    await expect(locator).toMatchAriaSnapshot(`
    - list
    - /children: equal
    - listitem: Feature A
    - listitem:
    - link "Feature B":
    - /url: "https://playwright.dev"
    `);

測試執行器

  • 新屬性 testProject.workers 允許指定用於測試專案的並行工作程序數。屬性 testConfig.workers 的全域限制仍然適用。
  • 新的 testConfig.failOnFlakyTests 選項可在檢測到任何不穩定測試時使測試執行失敗,類似於 --fail-on-flaky-tests。這對於 CI/CD 環境很有用,您希望確保所有測試在部署前都是穩定的。
  • 新屬性 testResult.annotations 包含每次測試重試的註釋。

其他

  • apiRequest.newContext() 中的新選項 maxRedirects 用於控制重定向的最大次數。
  • HTML 報告器現在支援透過 !@my-tag!my-file.spec.ts!p:my-project 進行否定過濾

重大變更

  • page.route() 這樣的方法中的全域 URL 模式不再支援 ?[]。我們建議改用正規表達式。
  • 方法 route.continue() 不再允許覆寫 Cookie 標頭。如果提供了 Cookie 標頭,它將被忽略,cookie 將從瀏覽器的 cookie 儲存中載入。要設定自訂 cookies,請使用 browserContext.addCookies()
  • macOS 13 現已棄用,將不再接收 WebKit 更新。請升級到更新的 macOS 版本以繼續受益於最新的 WebKit 改進。

瀏覽器版本

  • Chromium 136.0.7103.25
  • Mozilla Firefox 137.0
  • WebKit 18.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 135
  • Microsoft Edge 135

版本 1.51

IndexedDB 的 StorageState

  • browserContext.storageState() 的新選項 indexedDB 允許儲存和還原 IndexedDB 內容。當您的應用程式使用 IndexedDB API 儲存驗證權杖時很有用,例如 Firebase Authentication。

    以下是遵循驗證指南的範例:

    tests/auth.setup.ts
    import { test as setup, expect } from '@playwright/test';
    import path from 'path';

    const authFile = path.join(__dirname, '../playwright/.auth/user.json');

    setup('authenticate', async ({ page }) => {
    await page.goto('/');
    // ... perform authentication steps ...

    // 確保儲存 indexedDB
    await page.context().storageState({ path: authFile, indexedDB: true });
    });

複製為提示

HTML 報告、追蹤檢視器和 UI 模式中錯誤的新「複製提示」按鈕。點擊以複製包含錯誤訊息和修復錯誤有用上下文的預填 LLM 提示。

複製提示

過濾可見元素

locator.filter() 的新選項 visible 允許僅匹配可見元素。

example.spec.ts
test('some test', async ({ page }) => {
// 忽略不可見的待辦事項。
const todoItems = page.getByTestId('todo-item').filter({ visible: true });
// 檢查正好有 3 個可見的。
await expect(todoItems).toHaveCount(3);
});

HTML 報告中的 Git 資訊

設定選項 testConfig.captureGitInfo 以將 git 資訊擷取到 testConfig.metadata 中。

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
captureGitInfo: { commit: true, diff: true }
});

可用時,HTML 報告將顯示此資訊:

報告中的 Git 資訊

測試步驟改進

測試步驟中現在可以使用新的 TestStepInfo 物件。您可以新增步驟附件或在某些條件下跳過步驟。

test('some test', async ({ page, isMobile }) => {
// 注意新的 "step" 參數:
await test.step('here is my step', async step => {
step.skip(isMobile, 'not relevant on mobile layouts');

// ...
await step.attach('my attachment', { body: 'some text' });
// ...
});
});

其他

瀏覽器版本

  • Chromium 134.0.6998.35
  • Mozilla Firefox 135.0
  • WebKit 18.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 133
  • Microsoft Edge 133

版本 1.50

測試執行器

  • 新選項 timeout 允許指定個別測試步驟的最大執行時間。逾時的步驟將導致測試執行失敗。

    test('some test', async ({ page }) => {
    await test.step('a step', async () => {
    // 此步驟可以與測試分別計時
    }, { timeout: 1000 });
    });
  • 新方法 test.step.skip() 可停用測試步驟的執行。

    test('some test', async ({ page }) => {
    await test.step('before running step', async () => {
    // Normal step
    });

    await test.step.skip('not yet ready', async () => {
    // 此步驟被跳過
    });

    await test.step('after running step', async () => {
    // 即使前一個步驟被跳過,此步驟仍會執行
    });
    });
  • 擴展了 expect(locator).toMatchAriaSnapshot() 以允許將 aria 快照儲存在獨立的 YAML 檔案中。

  • 新增方法 expect(locator).toHaveAccessibleErrorMessage() 用來斷言定位器指向具有指定 aria errormessage 的元素。

  • 選項 testConfig.updateSnapshots 新增了設定列舉值 changedchanged 只更新已變更的快照,而 all 現在會更新所有快照,無論是否有任何差異。

  • 新選項 testConfig.updateSourceMethod 定義當配置 testConfig.updateSnapshots 時更新原始碼的方式。新增了將變更寫入原始碼的 overwrite3-way 模式,除了現有建立補丁檔案的 patch 模式。

    npx playwright test --update-snapshots=changed --update-source-方法=3way
  • 選項 testConfig.webServer 新增了 gracefulShutdown 欄位,用於指定除預設 SIGKILL 之外的處理程序終止訊號。

  • Exposed testStep.attachments from the reporter API to allow retrieval of all attachments created by that step.

  • 新選項 pathTemplate 用於 testConfig.expect 配置中的 toHaveScreenshottoMatchAriaSnapshot 斷言。

UI 更新

  • 更新的預設 HTML 報告器以改善附件顯示。
  • Codegen 中新增用於選取元素以產生 aria 快照的按鈕。
  • 其他詳細資訊(如按下的按鍵)現在會與追蹤中的動作 API 呼叫一起顯示。
  • 在追蹤中顯示 canvas 內容容易出錯。顯示功能現在預設停用,可透過 Display canvas content UI 設定啟用。
  • CallNetwork 面板現在顯示額外的時間資訊。

重大變更

瀏覽器版本

  • Chromium 133.0.6943.16
  • Mozilla Firefox 134.0
  • WebKit 18.2

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 132
  • Microsoft Edge 132

版本 1.49

Aria 快照

新斷言 expect(locator).toMatchAriaSnapshot() 透過與以 YAML 表示的預期無障礙樹進行比較來驗證頁面結構。

await page.goto('https://playwright.dev');
await expect(page.locator('body')).toMatchAriaSnapshot(`
- banner:
- heading /Playwright enables reliable/ [level=1]
- link "開始使用"
- link "Star microsoft/playwright on GitHub"
- main:
- img "Browsers (Chromium, Firefox, WebKit)"
- heading "Any browser • Any platform • One API"
`);

您可以使用測試產生器產生此斷言,並使用 --update-snapshots 命令列旗標更新預期的快照。

aria 快照指南中了解更多。

測試執行器

Breaking: chromemsedge 頻道切換到新的無頭模式

如果您在 playwright.config.ts 中使用以下任一通道,此變更會影響您:

  • chrome, chrome-dev, chrome-beta, or chrome-canary
  • msedge, msedge-dev, msedge-beta, or msedge-canary

我需要做什麼?

更新到 Playwright v1.49 後,執行您的測試套件。如果仍然通過,您就可以繼續。如果沒有,您可能需要更新快照,並調整一些關於 PDF 檢視器和擴充功能的測試程式碼。請參閱 issue #33566 以取得更多詳細資訊。

其他重大變更

  • Ubuntu 20.04 和 Debian 11 上的 WebKit 將不再有更新。我們建議將您的作業系統更新到較新版本。
  • 套件 @playwright/experimental-ct-vue2 將不再更新。
  • 套件 @playwright/experimental-ct-solid 將不再更新。

嘗試新的 Chromium 無頭模式

您可以透過使用 'chromium' 頻道選擇新的無頭模式。如 官方 Chrome 文件所述

另一方面,新的無頭模式是真正的 Chrome 瀏覽器,因此更真實、可靠,並提供更多功能。這使其更適合高精度的端到端網頁應用程式測試或瀏覽器擴充功能測試。

請參閱...以取得更多詳細資訊.

測試執行器

  • 新的 CLI 選項 --fail-on-flaky-tests 會在任何不穩定測試時將結束代碼設為 1。請注意,預設情況下,當所有失敗的測試在重試後恢復時,測試執行器會以代碼 0 結束。使用此選項時,在這種情況下測試執行將失敗。

  • 新的環境變數 PLAYWRIGHT_FORCE_TTY 控制內建 listlinedot 報告器是否假設為即時終端。例如,當您的 CI 環境無法良好處理 ANSI 控制序列時,這可能有助於停用 tty 行為。或者,即使沒有即時終端存在,如果您計劃後處理輸出並處理控制序列,您也可以啟用 tty 行為。

    # Avoid TTY features that output ANSI control sequences
    PLAYWRIGHT_FORCE_TTY=0 npx playwright test

    # Enable TTY features, assuming a terminal width 80
    PLAYWRIGHT_FORCE_TTY=80 npx playwright test
  • 新選項 testConfig.respectGitIgnoretestProject.respectGitIgnore 控制在搜尋測試時是否排除符合 .gitignore 模式的檔案。

  • 新屬性 timeout 現在可用於自訂 expect 比對器。此屬性會考慮 playwright.config.tsexpect.configure()

    import { expect as baseExpect } from '@playwright/test';

    export const expect = baseExpect.extend({
    async toHaveAmount(locator: Locator, expected: number, options?: { timeout?: number }) {
    // 當未指定 timeout 選項時,使用設定檔的逾時設定。
    const timeout = options?.timeout ?? this.timeout;
    // ... implement the assertion ...
    },
    });

其他

  • 方法 locator.setInputFiles() 現在支援為 <input type=file webkitdirectory> 元素上傳目錄。

    await page.getByLabel('Upload directory').setInputFiles(path.join(__dirname, 'mydir'));
  • 多個方法(如 locator.click() or locator.press() 現在支援a ControlOrMeta modifier key. 此鍵 對應到 Meta on macOS and 對應到 Control on Windows and Linux.

    // Press the common keyboard shortcut Control+S or Meta+S to trigger a "Save" operation.
    await page.keyboard.press('ControlOrMeta+S');
  • 新屬性 httpCredentials.sendapiRequest.newContext() 中,允許永遠傳送 Authorization 標頭或僅在回應 401 Unauthorized 時傳送。

  • 新選項 reasonapiRequestContext.dispose() 中,將被包含在因內容處置而中斷的進行中作業的錯誤訊息中。

  • 新選項 hostbrowserType.launchServer() 中,允許在特定位址上接受 websocket 連線,而不是未指定的 0.0.0.0

  • Playwright 現在支援在 Ubuntu 24.04 上的 Chromium、Firefox 和 WebKit。

  • v1.45 是最後一個接收 macOS 12 Monterey WebKit 更新的版本。請更新 macOS 以繼續使用最新的 WebKit。

瀏覽器版本

  • Chromium 127.0.6533.5
  • Mozilla Firefox 127.0
  • WebKit 17.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 126
  • Microsoft Edge 126

版本 1.44

新的 API

無障礙斷言

  • expect(locator).toHaveAccessibleName() 檢查元素是否具有指定的無障礙名稱:

    const locator = page.getByRole('button');
    await expect(locator).toHaveAccessibleName('Submit');
  • expect(locator).toHaveAccessibleDescription() 檢查元素是否具有指定的無障礙描述:

    const locator = page.getByRole('button');
    await expect(locator).toHaveAccessibleDescription('Upload a photo');
  • expect(locator).toHaveRole() 檢查元素是否具有指定的 ARIA 角色:

    const locator = page.getByTestId('save-button');
    await expect(locator).toHaveRole('button');

定位器處理器

const locator = page.getByText('This interstitial covers the button');
await page.addLocatorHandler(locator, async overlay => {
await overlay.locator('#close').click();
}, { times: 3, noWaitAfter: true });
// 執行可能被覆蓋層中斷的測試。
// ...
await page.removeLocatorHandler(locator);

其他選項

  • multipart 選項在 apiRequestContext.fetch() 中現在接受 FormData 並支援具有相同名稱的重複欄位。

    const formData = new FormData();
    formData.append('file', new File(['let x = 2024;'], 'f1.js', { type: 'text/javascript' }));
    formData.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));
    context.request.post('https://example.com/uploadFiles', {
    multipart: formData
    });
  • expect(callback).toPass({ intervals }) 現在可以透過 expect.toPass.intervals 選項在 testConfig.expect 中全域配置或在 testProject.expect 中按專案配置。

  • expect(page).toHaveURL(url) 現在支援 ignoreCase 選項.

  • testProject.ignoreSnapshots 允許按專案配置是否跳過截圖預期。

報告器 API

  • 新方法 suite.entries() 按宣告順序回傳子測試套件和測試案例。suite.typetestCase.type 可以用來區分清單中的測試案例和套件。
  • Blob 報告器現在允許使用單一選項 outputFile 覆寫報告檔案路徑。相同的選項也可以指定為 PLAYWRIGHT_BLOB_OUTPUT_FILE 環境變數,這在 CI/CD 上可能更方便。
  • JUnit reporter 現在支援 includeProjectInTestName 選項.

命令列

  • --last-failed CLI 選項,用於僅執行上次執行中失敗的測試。

    First run all tests:

    $ npx playwright test

    Running 103 tests using 5 workers
    ...
    2 failed
    [chromium] › my-test.spec.ts:8:5 › two ─────────────────────────────────────────────────────────
    [chromium] › my-test.spec.ts:13:5 › three ──────────────────────────────────────────────────────
    101 passed (30.0s)

    現在修復失敗的測試,並使用 --last-failed 選項再次執行 Playwright:

    $ npx playwright test --last-failed

    Running 2 tests using 2 workers
    2 passed (1.2s)

瀏覽器版本

  • Chromium 125.0.6422.14
  • Mozilla Firefox 125.0.1
  • WebKit 17.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 124
  • Microsoft Edge 124

版本 1.43

新的 API

  • 方法 browserContext.clearCookies() 現在支援篩選器 to remove only some cookies.

    // Clear all cookies.
    await context.clearCookies();
    // New: clear cookies with a particular name.
    await context.clearCookies({ name: 'session-id' });
    // New: clear cookies for a particular domain.
    await context.clearCookies({ domain: 'my-origin.com' });
  • testOptions.trace 的新模式 retain-on-first-failure。在此模式下,會記錄每個測試的首次執行追蹤,但不記錄重試。當測試執行失敗時,保留追蹤檔案,否則移除。

    import { defineConfig } from '@playwright/test';

    export default defineConfig({
    use: {
    trace: 'retain-on-first-failure',
    },
    });
  • 新屬性 testInfo.tags 在測試執行期間公開測試標籤。

    test('example', async ({ page }) => {
    console.log(test.info().tags);
    });
  • 新方法 locator.contentFrame()Locator 物件轉換為 FrameLocator。當您在某處獲得 Locator 物件,然後想要與框架內的內容互動時,這會很有用。

    const locator = page.locator('iframe[name="embedded"]');
    // ...
    const frameLocator = locator.contentFrame();
    await frameLocator.getByRole('button').click();
  • 新方法 frameLocator.owner()FrameLocator 物件轉換為 Locator。當您在某處獲得 FrameLocator 物件,然後想要與 iframe 元素互動時,這會很有用。

    const frameLocator = page.frameLocator('iframe[name="embedded"]');
    // ...
    const locator = frameLocator.owner();
    await expect(locator).toBeVisible();

UI 模式更新

Playwright UI Mode

  • 在測試清單中查看標籤。
  • 透過輸入 @fast 或點擊標籤本身來按標籤篩選。
  • 新的快捷鍵:
    • "F5" 執行測試。
    • "Shift F5" 停止執行測試。
    • "Ctrl `" 切換測試輸出。

瀏覽器版本

  • Chromium 124.0.6367.8
  • Mozilla Firefox 124.0
  • WebKit 17.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 123
  • Microsoft Edge 123

版本 1.42

新的 API

  • 新方法 page.addLocatorHandler() 註冊一個回呼函數,當指定元素變為可見且可能阻止 Playwright 動作時會被呼叫。回呼函數可以移除覆蓋層。以下是一個在 cookie 對話方塊出現時關閉它的範例:
// Setup the handler.
await page.addLocatorHandler(
page.getByRole('heading', { name: 'Hej! You are in control of your cookies.' }),
async () => {
await page.getByRole('button', { name: 'Accept all' }).click();
});
// Write the test as usual.
await page.goto('https://www.ikea.com/');
await page.getByRole('link', { name: 'Collection of blue and white' }).click();
await expect(page.getByRole('heading', { name: 'Light and easy' })).toBeVisible();
electronApp.on('console', async msg => {
const values = [];
for (const arg of msg.args())
values.push(await arg.jsonValue());
console.log(...values);
});
await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));
  • 新語法 用於為測試新增標籤(測試標題中的 @-token 仍然支援):
test('test customer login', {
tag: ['@fast', '@login'],
}, async ({ page }) => {
// ...
});

使用 --grep 命令列選項僅執行具有特定標籤的測試。

npx playwright test --grep @fast
  • --project command line flag 現在支援 '*' wildcard:
npx playwright test --project='*mobile*'
test('test full report', {
annotation: [
{ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/23180' },
{ type: 'docs', description: 'https://playwright.dev/docs/test-annotations#tag-tests' },
],
}, async ({ page }) => {
// ...
});

公告

  • ⚠️ 不再支援Ubuntu 18。

瀏覽器版本

  • Chromium 123.0.6312.4
  • Mozilla Firefox 123.0
  • WebKit 17.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 122
  • Microsoft Edge 123

版本 1.41

新的 API

瀏覽器版本

  • Chromium 121.0.6167.57
  • Mozilla Firefox 121.0
  • WebKit 17.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 120
  • Microsoft Edge 120

版本 1.40

測試產生器更新

Playwright Test Generator

新的產生斷言工具:

以下是產生的測試與斷言範例:

import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
await page.goto('https://playwright.dev/');
await page.getByRole('link', { name: '開始使用' }).click();
await expect(page.getByLabel('Breadcrumbs').getByRole('list')).toContainText('Installation');
await expect(page.getByLabel('Search')).toBeVisible();
await page.getByLabel('Search').click();
await page.getByPlaceholder('Search docs').fill('locator');
await expect(page.getByPlaceholder('Search docs')).toHaveValue('locator');
});

新的 API

其他變更

瀏覽器版本

  • Chromium 120.0.6099.28
  • Mozilla Firefox 119.0
  • WebKit 17.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 119
  • Microsoft Edge 119

版本 1.39

為您的 expect 新增自定義比對器

您可以透過提供自定義匹配器來擴展 Playwright 斷言。這些匹配器將在 expect 物件上可用。

test.spec.ts
import { expect as baseExpect } from '@playwright/test';
export const expect = baseExpect.extend({
async toHaveAmount(locator: Locator, expected: number, options?: { timeout?: number }) {
// ... see documentation for how to write matchers.
},
});

test('pass', async ({ page }) => {
await expect(page.getByTestId('cart')).toHaveAmount(5);
});

查看完整範例的文件。

合併測試佈置

您現在可以合併來自多個檔案或模組的測試佈置:

fixtures.ts
import { mergeTests } from '@playwright/test';
import { test as dbTest } from 'database-test-utils';
import { test as a11yTest } from 'a11y-test-utils';

export const test = mergeTests(dbTest, a11yTest);
test.spec.ts
import { test } from './fixtures';

test('passes', async ({ database, page, a11y }) => {
// use database and a11y fixtures.
});

合併自定義 expect 比對器

您現在可以從多個檔案或模組合併自訂的 expect 比對器:

fixtures.ts
import { mergeTests, mergeExpects } from '@playwright/test';
import { test as dbTest, expect as dbExpect } from 'database-test-utils';
import { test as a11yTest, expect as a11yExpect } from 'a11y-test-utils';

export const test = mergeTests(dbTest, a11yTest);
export const expect = mergeExpects(dbExpect, a11yExpect);
test.spec.ts
import { test, expect } from './fixtures';

test('passes', async ({ page, database }) => {
await expect(database).toHaveDatabaseUser('admin');
await expect(page).toPassA11yAudit();
});

隱藏實作細節:框架測試步驟

您可以mark a test.step() as "boxed" so that errors inside it point to the step call site.

async function login(page) {
await test.step('login', async () => {
// ...
}, { box: true }); // Note the "box" 選項 here.
}
Error: Timed out 5000ms waiting for expect(locator).toBeVisible()
... error details omitted ...

14 | await page.goto('https://github.com/login');
> 15 | await login(page);
| ^
16 | });

請參閱 test.step() 文件以取得完整範例。

新的 API

瀏覽器版本

  • Chromium 119.0.6045.9
  • Mozilla Firefox 118.0.1
  • WebKit 17.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 118
  • Microsoft Edge 118

版本 1.38

UI 模式更新

Playwright UI Mode

  1. 放大到時間範圍。
  2. 網路面板重新設計。

新的 API

棄用

重大變更:Playwright 不再自動下載瀏覽器

Note: If you are using @playwright/test package, this change does not affect you.

Playwright 建議使用 @playwright/test 套件,並透過 npx playwright install 命令下載瀏覽器。如果您遵循此建議,則沒有任何變更會影響您。

然而,在 v1.38 之前,安裝 playwright 套件而非 @playwright/test 會自動下載瀏覽器。這已不再如此,我們建議透過 npx playwright install 命令明確下載瀏覽器。

v1.37 and earlier

playwright package was downloading browsers during npm install, while @playwright/test was not.

v1.38 and later

playwright and @playwright/test packages do not download browsers during npm install.

Recommended migration

npm install 後執行 npx playwright install 來下載瀏覽器。例如,在您的 CI 配置中:

- run: npm ci
- run: npx playwright install --with-deps

Alternative migration 選項 - not recommended

新增 @playwright/browser-chromium@playwright/browser-firefox@playwright/browser-webkit 作為相依性。這些套件會在 npm install 期間下載相應的瀏覽器。請確保所有 playwright 套件的版本保持同步:

// package.json
{
"devDependencies": {
"playwright": "1.38.0",
"@playwright/browser-chromium": "1.38.0",
"@playwright/browser-firefox": "1.38.0",
"@playwright/browser-webkit": "1.38.0"
}
}

瀏覽器版本

  • Chromium 117.0.5938.62
  • Mozilla Firefox 117.0
  • WebKit 17.0

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 116
  • Microsoft Edge 116

版本 1.37

新的 npx playwright merge-reports 工具

如果您在多個分片上執行測試,您現在可以使用新的 merge-reports CLI 工具將所有報告合併為單一 HTML 報告(或任何其他報告)。

使用 merge-reports 工具需要以下步驟:

  1. Adding a new "blob" reporter to the config when running on CI:

    playwright.config.ts
    export default defineConfig({
    testDir: './tests',
    reporter: process.env.CI ? 'blob' : 'html',
    });

    The "blob" reporter will produce ".zip" files that contain all the information about the test run.

  2. Copying all "blob" reports in a single shared location and running npx playwright merge-reports:

npx playwright merge-reports --reporter html ./all-blob-reports

我們的文件中閱讀更多。

📚 Debian 12 Bookworm 支援

Playwright 現在支援 Debian 12 Bookworm 在 x86_64 和 arm64 上的 Chromium、Firefox 和 WebKit。如果您遇到任何問題,請告訴我們!

Linux 支援如下:

Ubuntu 20.04Ubuntu 22.04Debian 11Debian 12
Chromium
WebKit
Firefox

UI 模式更新

  • UI 模式現在遵循專案依賴性。您可以透過在專案清單中勾選/取消勾選來控制要遵循哪些依賴性。
  • 來自測試的控制台日誌現在會顯示在控制台標籤中。

瀏覽器版本

  • Chromium 116.0.5845.82
  • Mozilla Firefox 115.0
  • WebKit 17.0

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 115
  • Microsoft Edge 115

版本 1.36

🏝️ 夏季維護版本。

瀏覽器版本

  • Chromium 115.0.5790.75
  • Mozilla Firefox 115.0
  • WebKit 17.0

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 114
  • Microsoft Edge 114

版本 1.35

重點

  • UI mode 現在可用 在 VSCode Playwright extension via a new "Show trace viewer" button:

    Playwright UI Mode

  • UI mode and trace viewer mark network requests handled with page.route()browserContext.route() handlers, as well as those issued via the API testing:

    Trace Viewer

  • 新選項 maskColor用於方法page.screenshot(), locator.screenshot(), expect(page).toHaveScreenshot()expect(locator).toHaveScreenshot() 以變更預設遮罩顏色:

    await page.goto('https://playwright.dev');
    await expect(page).toHaveScreenshot({
    mask: [page.locator('img')],
    maskColor: '#00FF00', // green
    });
  • 新的 uninstall CLI 命令用於解除安裝瀏覽器二進位檔:

    $ npx playwright uninstall # remove browsers installed by this installation
    $ npx playwright uninstall --all # remove all ever-install Playwright browsers
  • Both UI mode and trace viewer now could be opened in a browser tab:

    $ npx playwright test --ui-port 0 # open UI mode in a tab on a random port
    $ npx playwright show-trace --port 0 # open trace viewer in tab on a random port

⚠️ 重大變更s

  • playwright-core binary got renamed from playwright to playwright-core. So if you use playwright-core CLI, make sure to update the name:

    $ npx playwright-core install # the new way to install browsers when using playwright-core

    This change does not affect @playwright/test and playwright package users.

瀏覽器版本

  • Chromium 115.0.5790.13
  • Mozilla Firefox 113.0
  • WebKit 16.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 114
  • Microsoft Edge 114

版本 1.34

重點

  • UI 模式現在顯示步驟、固定裝置和附件: UI Mode attachments

  • 新屬性 testProject.teardown,用於指定在此專案和所有相依專案完成後需要執行的專案。Teardown 對於清理此專案獲取的任何資源很有用。

    常見的模式是 setup 相依性與對應的 teardown

    playwright.config.ts
    import { defineConfig } from '@playwright/test';

    export default defineConfig({
    projects: [
    {
    name: 'setup',
    testMatch: /global.setup\.ts/,
    teardown: 'teardown',
    },
    {
    name: 'teardown',
    testMatch: /global.teardown\.ts/,
    },
    {
    name: 'chromium',
    use: devices['Desktop Chrome'],
    dependencies: ['setup'],
    },
    {
    name: 'firefox',
    use: devices['Desktop Firefox'],
    dependencies: ['setup'],
    },
    {
    name: 'webkit',
    use: devices['Desktop Safari'],
    dependencies: ['setup'],
    },
    ],
    });
  • 新方法 expect.configure 以建立具有自己預設值(如 timeoutsoft)的預配置 expect 實例。

    const slowExpect = expect.configure({ timeout: 10000 });
    await slowExpect(locator).toHaveText('Submit');

    // Always do soft assertions.
    const softExpect = expect.configure({ soft: true });
  • 新選項 stderrstdouttestConfig.webServer 中以配置輸出處理:

    playwright.config.ts
    import { defineConfig } from '@playwright/test';

    export default defineConfig({
    // 在開始測試前執行您的本地開發伺服器
    webServer: {
    command: 'npm run start',
    url: 'http://127.0.0.1:3000',
    reuseExistingServer: !process.env.CI,
    stdout: 'pipe',
    stderr: 'pipe',
    },
    });
  • 新的 locator.and() 用於建立符合兩個定位器的定位器。

    const button = page.getByRole('button').and(page.getByTitle('Subscribe'));
  • 新事件 browserContext.on('console')browserContext.on('dialog') 用於訂閱來自給定瀏覽器上下文中任何頁面的對話框和主控台訊息。使用新方法 consoleMessage.page()dialog.page() 精確定位事件來源。

⚠️ 重大變更s

  • npx playwright test no longer works if you install both playwright and @playwright/test. There's no need to install both, since you can always import browser automation APIs from @playwright/test directly:

    automation.ts
    import { chromium, firefox, webkit } from '@playwright/test';
    /* ... */
  • Node.js 14 is no longer supported since it reached its end-of-life on April 30, 2023.

瀏覽器版本

  • Chromium 114.0.5735.26
  • Mozilla Firefox 113.0
  • WebKit 16.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 113
  • Microsoft Edge 113

版本 1.33

定位器更新

  • 使用 locator.or() 建立符合兩個定位器其中之一的定位器。考慮這樣的場景:您想要點選「New email」按鈕,但有時會出現安全設定對話框。在這種情況下,您可以等待「New email」按鈕或對話框,並相應地採取行動:

    const newEmail = page.getByRole('button', { name: 'New email' });
    const dialog = page.getByText('Confirm security settings');
    await expect(newEmail.or(dialog)).toBeVisible();
    if (await dialog.isVisible())
    await page.getByRole('button', { name: 'Dismiss' }).click();
    await newEmail.click();
  • locator.filter() 中使用新選項 hasNothasNotText 來尋找不符合特定條件的元素。

    const rowLocator = page.locator('tr');
    await rowLocator
    .filter({ hasNotText: 'text in column 1' })
    .filter({ hasNot: page.getByRole('button', { name: 'column 2 button' }) })
    .screenshot();
  • 使用新的網頁優先斷言 expect(locator).toBeAttached() 確保元素存在於頁面的 DOM 中。不要與 expect(locator).toBeVisible() 混淆,後者確保元素既附加又可見。

新的 API

⚠️ 重大變更

  • mcr.microsoft.com/playwright:v1.33.0 現在提供基於 Ubuntu Jammy 的 Playwright 映像。若要使用基於 focal 的映像,請改用 mcr.microsoft.com/playwright:v1.33.0-focal

瀏覽器版本

  • Chromium 113.0.5672.53
  • Mozilla Firefox 112.0
  • WebKit 16.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 112
  • Microsoft Edge 112

版本 1.32

介紹 UI 模式(預覽)

新的 UI 模式 讓您可以探索、執行和除錯測試。內建觀察模式。

Playwright UI Mode

使用新的旗標 --ui 啟用:

npx playwright test --ui

新的 API

⚠️ 重大變更 in component tests

注意:僅適用於元件測試,不影響端對端測試。

  • @playwright/experimental-ct-react 現在支援 React 18 only.
  • 如果您正在使用 React 16 或 17 執行元件測試,請將 @playwright/experimental-ct-react 替換為 @playwright/experimental-ct-react17

瀏覽器版本

  • Chromium 112.0.5615.29
  • Mozilla Firefox 111.0
  • WebKit 16.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 111
  • Microsoft Edge 111

版本 1.31

新的 API

  • 新屬性 testProject.dependencies 以配置專案之間的依賴性。

    使用相依性允許全域設定產生追蹤和其他工件,在測試報告中查看設定步驟等。

    playwright.config.ts
    import { defineConfig } from '@playwright/test';

    export default defineConfig({
    projects: [
    {
    name: 'setup',
    testMatch: /global.setup\.ts/,
    },
    {
    name: 'chromium',
    use: devices['Desktop Chrome'],
    dependencies: ['setup'],
    },
    {
    name: 'firefox',
    use: devices['Desktop Firefox'],
    dependencies: ['setup'],
    },
    {
    name: 'webkit',
    use: devices['Desktop Safari'],
    dependencies: ['setup'],
    },
    ],
    });
  • 新的 assertion expect(locator).toBeInViewport() ensures that locator points to an element that intersects viewport, according to the intersection observer API.

    const button = page.getByRole('button');

    // Make sure at least some part of element intersects viewport.
    await expect(button).toBeInViewport();

    // Make sure element is fully outside of viewport.
    await expect(button).not.toBeInViewport();

    // Make sure that at least half of the element intersects viewport.
    await expect(button).toBeInViewport({ ratio: 0.5 });

其他

  • 追蹤檢視器中的 DOM 快照現在可以在單獨的視窗中開啟。
  • 新方法 defineConfig to be used in playwright.config.
  • 新選項 maxRedirects 用於方法 route.fetch().
  • Playwright 現在支援 Debian 11 arm64.
  • Official docker images現在include Node 18 instead of Node 16.

⚠️ 重大變更 in component tests

注意:僅適用於元件測試,不影響端對端測試。

元件測試playwright-ct.config 配置檔現在需要呼叫 defineConfig

// Before

import { type PlaywrightTestConfig, devices } from '@playwright/experimental-ct-react';
const config: PlaywrightTestConfig = {
// ... config goes here ...
};
export default config;

config 變數定義替換為 defineConfig 呼叫:

// After

import { defineConfig, devices } from '@playwright/experimental-ct-react';
export default defineConfig({
// ... config goes here ...
});

瀏覽器版本

  • Chromium 111.0.5563.19
  • Mozilla Firefox 109.0
  • WebKit 16.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 110
  • Microsoft Edge 110

版本 1.30

瀏覽器版本

  • Chromium 110.0.5481.38
  • Mozilla Firefox 108.0.2
  • WebKit 16.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 109
  • Microsoft Edge 109

版本 1.29

新的 API

  • 新方法 route.fetch() 和新選項 json 用於route.fulfill():

    await page.route('**/api/settings', async route => {
    // Fetch original settings.
    const response = await route.fetch();

    // Force settings theme to a predefined value.
    const json = await response.json();
    json.theme = 'Solorized';

    // Fulfill with modified data.
    await route.fulfill({ json });
    });
  • 新方法 locator.all() to iterate over all matching elements:

    // Check all checkboxes!
    const checkboxes = page.getByRole('checkbox');
    for (const checkbox of await checkboxes.all())
    await checkbox.check();
  • locator.selectOption() matches現在by value or label:

    <select multiple>
    <選項 value="red">Red</選項>
    <選項 value="green">Green</選項>
    <選項 value="blue">Blue</選項>
    </select>
    await element.selectOption('Red');
  • Retry blocks of code until all assertions pass:

    await expect(async () => {
    const response = await page.request.get('https://api.example.com');
    await expect(response).toBeOK();
    }).toPass();

    我們的文件中閱讀更多。

  • Automatically capture full page screenshot on test failure:

    playwright.config.ts
    import { defineConfig } from '@playwright/test';
    export default defineConfig({
    use: {
    screenshot: {
    mode: 'only-on-failure',
    fullPage: true,
    }
    }
    });

其他

瀏覽器版本

  • Chromium 109.0.5414.46
  • Mozilla Firefox 107.0
  • WebKit 16.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 108
  • Microsoft Edge 108

版本 1.28

Playwright 工具

  • Record at Cursor in VSCode. 您可以run the test, position the cursor at the end of the test and continue generating the test.

New VSCode Extension

  • Live Locators in VSCode. 您可以hover and edit locators in VSCode to get them highlighted in the opened browser.
  • Live Locators in CodeGen. Generate a locator for any element on the page using "Explore" tool.

Locator Explorer

  • Codegen and Trace Viewer Dark Theme. Automatically picked up from operating system settings.

Dark Theme

測試執行器

新的 API

瀏覽器版本

  • Chromium 108.0.5359.29
  • Mozilla Firefox 106.0
  • WebKit 16.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 107
  • Microsoft Edge 107

版本 1.27

定位器

使用這些新 API 撰寫定位器是一種樂趣:

await page.getByLabel('User Name').fill('John');

await page.getByLabel('Password').fill('secret-password');

await page.getByRole('button', { name: 'Sign in' }).click();

await expect(page.getByText('Welcome, John!')).toBeVisible();

LocatorFrameLocatorFrame 類別也都提供相同的方法。

其他重點

  • workers 選項在 playwright.config.ts 中現在接受百分比字串以使用部分可用的 CPU。您也可以在命令列中傳遞它:

    npx playwright test --workers=20%
  • 新選項s host and port for the html reporter.

    import { defineConfig } from '@playwright/test';

    export default defineConfig({
    reporter: [['html', { host: 'localhost', port: '9223' }]],
    });
  • 新欄位 FullConfig.configFile 可用於測試報告器,用於指定設定檔的路徑(如果有的話)。

  • 如 v1.25 中所宣布,Ubuntu 18 將在 2022 年 12 月起不再受支援。除此之外,從下一個 Playwright 版本開始,Ubuntu 18 上將不會有 WebKit 更新。

行為變更

  • expect(locator).toHaveAttribute() 使用空值不再比對缺少的屬性。例如,當 button 沒有 disabled 屬性時,以下程式碼片段將會成功。

    await expect(page.getByRole('button')).toHaveAttribute('disabled', '');
  • 命令列選項 --grep--grep-invert 先前錯誤地忽略了設定中指定的 grepgrepInvert 選項。現在它們會一起套用。

瀏覽器版本

  • Chromium 107.0.5304.18
  • Mozilla Firefox 105.0.1
  • WebKit 16.0

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 106
  • Microsoft Edge 106

版本 1.26

斷言

其他重點

  • 新選項 maxRedirects for apiRequestContext.get()和其他方法以limit redirect count.
  • 新的命令列旗標 --pass-with-no-tests,允許在找不到檔案時讓測試套件通過。
  • 新的命令列旗標 --ignore-snapshots 用於跳過快照預期,例如 expect(value).toMatchSnapshot()expect(page).toHaveScreenshot()

行為變更

許多 Playwright API 已經支援 waitUntil: 'domcontentloaded' 選項。例如:

await page.goto('https://playwright.dev', {
waitUntil: 'domcontentloaded',
});

在 1.26 之前,這將等待所有 iframe 觸發 DOMContentLoaded 事件。

為了與網頁規範保持一致,'domcontentloaded' 值只會等待目標框架觸發 'DOMContentLoaded' 事件。使用 waitUntil: 'load' 來等待所有 iframe。

瀏覽器版本

  • Chromium 106.0.5249.30
  • Mozilla Firefox 104.0
  • WebKit 16.0

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 105
  • Microsoft Edge 105

版本 1.25

VSCode Extension

  • Watch your tests running live & keep devtools open.
  • Pick selector.
  • Record new test from current page state.

vscode extension screenshot

測試執行器

  • test.step() now 回傳 the value of the step function:

    test('should work', async ({ page }) => {
    const pageTitle = await test.step('get title', async () => {
    await page.goto('https://playwright.dev');
    回傳 await page.title();
    });
    console.log(pageTitle);
    });
  • Added test.describe.fixme().

  • New 'interrupted' test status.

  • Enable tracing via CLI flag: npx playwright test --trace=on.

公告

  • 🎁 我們現在發佈 Ubuntu 22.04 Jammy Jellyfish docker 映像:mcr.microsoft.com/playwright:v1.34.0-jammy
  • 🪦 這是最後一個支援macOS 10.15 的版本(自 1.21 起已棄用)。
  • 🪦 這是最後一個支援Node.js 12 的版本,我們建議升級到 Node.js LTS (16)。
  • ⚠️ Ubuntu 18 現已棄用,將從 2022 年 12 月起不再受支援。

瀏覽器版本

  • Chromium 105.0.5195.19
  • Mozilla Firefox 103.0
  • WebKit 16.0

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 104
  • Microsoft Edge 104

版本 1.24

🌍 Multiple Web Servers in playwright.config.ts

透過傳遞配置陣列來啟動多個網頁伺服器、資料庫或其他程序:

playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: [
{
command: 'npm run start',
url: 'http://127.0.0.1:3000',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
{
command: 'npm run backend',
url: 'http://127.0.0.1:3333',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
}
],
use: {
baseURL: 'http://localhost:3000/',
},
});

🐂 Debian 11 Bullseye Support

Playwright 現在支援 Debian 11 Bullseye 在 x86_64 上的 Chromium、Firefox 和 WebKit。如果您遇到任何問題,請告訴我們!

Linux support looks like this:

| | Ubuntu 20.04 | Ubuntu 22.04 | Debian 11 | :--- | :---: | :---: | :---: | :---: | | Chromium | ✅ | ✅ | ✅ | | WebKit | ✅ | ✅ | ✅ | | Firefox | ✅ | ✅ | ✅ |

🕵️ Anonymous Describe

現在可以呼叫 test.describe() 來建立沒有標題的測試套件。這對於使用 test.use() 為一組測試提供共同選項很有用。

test.describe(() => {
test.use({ colorScheme: 'dark' });

test('one', async ({ page }) => {
// ...
});

test('two', async ({ page }) => {
// ...
});
});

🧩 Component Tests Update

Playwright 1.24 組件測試引入了 beforeMountafterMount 鉤子。使用這些來為測試配置您的應用程式。

例如,這可以用來在 Vue.js 中設定 App router:

src/component.spec.ts
import { test } from '@playwright/experimental-ct-vue';
import { Component } from './mycomponent';

test('should work', async ({ mount }) => {
const component = await mount(Component, {
hooksConfig: {
/* anything to configure your app */
}
});
});
playwright/index.ts
import { router } from '../router';
import { beforeMount } from '@playwright/experimental-ct-vue/hooks';

beforeMount(async ({ app, hooksConfig }) => {
app.use(router);
});

A similar configuration in Next.js would look like this:

src/component.spec.jsx
import { test } from '@playwright/experimental-ct-react';
import { Component } from './mycomponent';

test('should work', async ({ mount }) => {
const component = await mount(<Component></Component>, {
// Pass mock value from test into `beforeMount`.
hooksConfig: {
router: {
query: { page: 1, per_page: 10 },
asPath: '/posts'
}
}
});
});
playwright/index.js
import router from 'next/router';
import { beforeMount } from '@playwright/experimental-ct-react/hooks';

beforeMount(async ({ hooksConfig }) => {
// Before mount, redefine useRouter to 回傳 mock value from test.
router.useRouter = () => hooksConfig.router;
});

版本 1.23

網路重播

現在您可以將網路流量錄製到 HAR 檔案中,並在測試中重複使用此流量。

將網路錄製到 HAR 檔案:

npx playwright open --save-har=github.har.zip https://github.com/microsoft

或者,您可以透過程式方式錄製 HAR:

const context = await browser.newContext({
recordHar: { path: 'github.har.zip' }
});
// ... do stuff ...
await context.close();

使用新方法 page.routeFromHAR()browserContext.routeFromHAR()HAR 檔案提供符合的回應:

await context.routeFromHAR('github.har.zip');

我們的文件中閱讀更多。

進階路由

您現在可以使用 route.fallback() 將路由委派給其他處理器。

請考慮以下範例:

// Remove a header from all requests.
test.beforeEach(async ({ page }) => {
await page.route('**/*', async route => {
const headers = await route.request().allHeaders();
delete headers['if-none-match'];
await route.fallback({ headers });
});
});

test('should work', async ({ page }) => {
await page.route('**/*', async route => {
if (route.request().resourceType() === 'image')
await route.abort();
else
await route.fallback();
});
});

請注意,新方法 page.routeFromHAR()browserContext.routeFromHAR() 也會參與路由處理,並且可以被延遲。

Web-First 斷言更新

元件測試更新

component testing with Playwright.

其他

  • 如果有阻礙您的 Service Worker,您現在可以透過新的上下文選項 serviceWorkers 輕鬆停用它:

    playwright.config.ts
    export default {
    use: {
    serviceWorkers: 'block',
    }
    };
  • Using .zip path for recordHar context 選項 自動壓縮 the resulting HAR:

    const context = await browser.newContext({
    recordHar: {
    path: 'github.har.zip',
    }
    });
  • 如果您打算手動編輯 HAR,請考慮使用僅記錄重播所需基本資訊的 "minimal" HAR 記錄模式:

    const context = await browser.newContext({
    recordHar: {
    path: 'github.har',
    mode: 'minimal',
    }
    });
  • Playwright 現在在 Ubuntu 22 amd64 和 Ubuntu 22 arm64 上執行。我們也發佈了新的 Docker 映像 mcr.microsoft.com/playwright:v1.34.0-jammy

⚠️ 重大變更s ⚠️

WebServer 現在如果對指定 URL 的請求具有以下任一 HTTP 狀態碼,就被視為「準備就緒」:

  • 200-299
  • 300-399 (new)
  • 400, 401, 402, 403 (new)

版本 1.22

重點

  • 元件測試(預覽)

    Playwright Test 現在可以 test your React, Vue.js or Svelte components. 您可以use all the features of Playwright Test (such as parallelization, emulation & debugging) while running components 在 real browsers.

    以下是典型的元件測試範例:

    App.spec.tsx
    import { test, expect } from '@playwright/experimental-ct-react';
    import App from './App';

    // Let's test component in a dark scheme!
    test.use({ colorScheme: 'dark' });

    test('should render', async ({ mount }) => {
    const component = await mount(<App></App>);

    // As with any Playwright test, assert locator text.
    await expect(component).toContainText('React');
    // Or do a screenshot 🚀
    await expect(component).toHaveScreenshot();
    // Or use any Playwright 方法
    await component.click();
    });

    我們的文件中閱讀更多。

  • 角色選擇器,允許依據其 ARIA roleARIA attributes無障礙名稱選取元素。

    // Click a button with accessible name "log in"
    await page.locator('role=button[name="log in"]').click();

    我們的文件中閱讀更多。

  • 新的 locator.filter() API 用於篩選現有定位器

    const buttons = page.locator('role=button');
    // ...
    const submitButton = buttons.filter({ hasText: 'Submit' });
    await submitButton.click();
  • 新的網頁優先斷言 expect(page).toHaveScreenshot()expect(locator).toHaveScreenshot(),等待螢幕截圖穩定並增強測試可靠性。

    The new assertions has screenshot-specific defaults, such as:

    • disables animations
    • uses CSS scale 選項
    await page.goto('https://playwright.dev');
    await expect(page).toHaveScreenshot();

    The new expect(page).toHaveScreenshot() saves screenshots at the same location as expect(value).toMatchSnapshot().

版本 1.21

重點

  • 新的角色選擇器,允許依據其 ARIA roleARIA attributes無障礙名稱選取元素。

    // Click a button with accessible name "log in"
    await page.locator('role=button[name="log in"]').click();

    我們的文件中閱讀更多。

  • page.screenshot() 中的新 scale 選項,用於產生較小尺寸的螢幕截圖。

  • page.screenshot() 中的新 caret 選項控制文字游標。預設為 "hide"

  • 新方法 expect.poll to wait for an arbitrary condition:

    // Poll the 方法 until it 回傳 an expected result.
    await expect.poll(async () => {
    const response = await page.request.get('https://api.example.com');
    回傳 response.status();
    }).toBe(200);

    expect.poll supports most synchronous matchers, like .toBe(), .toContain(), etc. 在我們的文件中閱讀更多。

行為變更

  • 在執行 TypeScript 測試時,ESM 支援現在預設啟用。不再需要 PLAYWRIGHT_EXPERIMENTAL_TS_ESM 環境變數。
  • mcr.microsoft.com/playwright docker 映像不再包含 Python。請使用 mcr.microsoft.com/playwright/python 作為預先安裝 Python 的 Playwright-ready docker 映像。
  • Playwright 現在透過 locator.setInputFiles() API 支援大型檔案上傳(數百 MB)。

瀏覽器版本

  • Chromium 101.0.4951.26
  • Mozilla Firefox 98.0.2
  • WebKit 15.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 100
  • Microsoft Edge 100

版本 1.20

重點

  • 新選項s用於方法page.screenshot(), locator.screenshot()elementHandle.screenshot():

    • 選項 animations: "disabled" 將所有 CSS 動畫和轉場重置為一致狀態
    • 選項 mask: Locator[] 遮罩指定的元素,在其上方覆蓋粉色 #FF00FF 方框。
  • expect().toMatchSnapshot() 現在支援anonymous snapshots: 當快照名稱缺少時, Playwright Test 將自動產生一個:

    expect('Web is Awesome <3').toMatchSnapshot();
  • New maxDiffPixels and maxDiffPixelRatio options for fine-grained screenshot comparison using expect().toMatchSnapshot():

    expect(await page.screenshot()).toMatchSnapshot({
    maxDiffPixels: 27, // allow no more than 27 different pixels.
    });

    testConfig.expect 中指定一次 maxDiffPixelsmaxDiffPixelRatio 是最方便的。

  • Playwright Test 現在新增 testConfig.fullyParallel 模式。預設情況下,Playwright Test 在檔案之間平行化。在完全平行模式中,單一檔案內的測試也會平行執行。您也可以使用 --fully-parallel 命令列標誌。

    playwright.config.ts
    export default {
    fullyParallel: true,
    };
  • testProject.greptestProject.grepInvert 現在可按專案配置。例如,您現在可以使用 grep 配置冒煙測試專案:

    playwright.config.ts
    export default {
    projects: [
    {
    name: 'smoke tests',
    grep: /@smoke/,
    },
    ],
    };
  • Trace Viewer現在shows API testing requests.

  • locator.highlight()視覺化地顯示element(s)以便更輕鬆地debugging.

公告

  • 我們現在發佈專用的 Python docker 映像 mcr.microsoft.com/playwright/python。如果您使用 Python,請切換到該映像。這是最後一個在我們的 javascript mcr.microsoft.com/playwright docker 映像中包含 Python 的版本。
  • v1.20 是最後一個為 macOS 10.15 Catalina 接收 WebKit 更新的版本。請更新 macOS 以繼續使用最新的 WebKit!

瀏覽器版本

  • Chromium 101.0.4921.0
  • Mozilla Firefox 97.0.1
  • WebKit 15.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 99
  • Microsoft Edge 99

版本 1.19

Playwright Test 更新

  • Playwright Test v1.19 現在支援 soft assertions. Failed soft assertions

    do not terminate test execution, but mark the test as failed.

    // Make a few checks that will not stop the test when failed...
    await expect.soft(page.locator('#status')).toHaveText('Success');
    await expect.soft(page.locator('#eta')).toHaveText('1 day');

    // ... and continue the test to check more things.
    await page.locator('#next-page').click();
    await expect.soft(page.locator('#title')).toHaveText('Make another order');

    我們的文件中閱讀更多

  • 您現在可以指定自定義期望訊息作為 expectexpect.soft 函數的第二個參數,例如:

    await expect(page.locator('text=Name'), 'should be logged in').toBeVisible();

    The error would look like this:

        Error: should be logged in

    Call log:
    - expect.toBeVisible 逾時 5000ms
    - waiting for "getByText('Name')"


    2 |
    3 | test('example test', async({ page }) => {
    > 4 | await expect(page.locator('text=Name'), 'should be logged in').toBeVisible();
    | ^
    5 | });
    6 |

    我們的文件中閱讀更多

  • 預設情況下,單一檔案中的測試會依序執行。如果您在單一檔案中有許多獨立的測試,您現在可以使用 test.describe.configure() 平行執行它們。

其他更新

Playwright Test 全域設定中的潛在重大變更

此變更不太可能影響您,如果您的測試持續運作如常,則無需採取任何動作。

我們注意到在極少數情況下,要執行的測試集合是透過環境變數在全域設定中配置的。我們也注意到一些應用程式在全域清理中對報告器的輸出進行後處理。如果您正在執行其中一項,了解更多

瀏覽器版本

  • Chromium 100.0.4863.0
  • Mozilla Firefox 96.0.1
  • WebKit 15.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 98
  • Microsoft Edge 98

版本 1.18

定位器改進

測試 API 改進

改進的 TypeScript 支援

  1. Playwright 測試現在遵循 tsconfig.jsonbaseUrlpaths,因此您可以使用別名
  2. 有一個新的環境變數 PW_EXPERIMENTAL_TS_ESM,允許在您的 TS 程式碼中匯入 ESM 模組,無需編譯步驟。在匯入 ESM 模組時,不要忘記 .js 後綴。如下執行您的測試:
npm i --save-dev @playwright/test@1.18.0-rc1
PW_EXPERIMENTAL_TS_ESM=1 npx playwright test

建立 Playwright

The npm init playwright command is now generally available for your use:

# Run from your project's root directory
npm init playwright@latest
# Or create a new project
npm init playwright@latest new-project

這將建立 Playwright 測試配置檔案,可選擇性地新增範例、GitHub Action 工作流程和第一個測試 example.spec.ts

新的 API 與變更

重大變更:自定義配置選項

自定義配置選項是用不同值參數化專案的便利方式。在此指南中了解更多。

以前,透過 test.extend() 引入的任何固件都可以在 testProject.use 配置區段中覆寫。例如,

// WRONG: THIS SNIPPET DOES NOT WORK SINCE v1.18.

// fixtures.js
const test = base.extend({
myParameter: 'default',
});

// playwright.config.js
module.exports = {
use: {
myParameter: 'value',
},
};

在配置檔中使佈置參數化的正確方式是在定義佈置時指定 選項: true。例如:

// CORRECT: THIS SNIPPET WORKS SINCE v1.18.

// fixtures.js
const test = base.extend({
// 標記為「選項: true」的 Fixtures 將取得在配置中指定的值,
// or fallback to the default value.
myParameter: ['default', { 選項: true }],
});

// playwright.config.js
module.exports = {
use: {
myParameter: 'value',
},
};

瀏覽器版本

  • Chromium 99.0.4812.0
  • Mozilla Firefox 95.0
  • WebKit 15.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 97
  • Microsoft Edge 97

版本 1.17

框架定位器

Playwright 1.17 引入了框架定位器 - 用於頁面上 iframe 的定位器。框架定位器捕獲足以擷取 iframe 然後在該 iframe 中定位元素的邏輯。框架定位器預設為嚴格模式,會等待 iframe 出現,並可用於 Web-First 斷言。

Graphics

框架定位器可以使用 page.frameLocator()locator.frameLocator() 方法建立。

const locator = page.frameLocator('#my-iframe').locator('text=Submit');
await locator.click();

我們的文件中閱讀更多。

追蹤檢視器更新

Playwright 追蹤檢視器現在可在線上使用https://trace.playwright.dev!只需拖放您的 trace.zip 檔案即可檢查其內容。

NOTE: trace files are not uploaded anywhere; trace.playwright.dev is a progressive web application that processes traces locally.

  • Playwright 測試追蹤現在預設包含原始碼(這些可以透過追蹤選項關閉)
  • 追蹤檢視器現在顯示測試名稱
  • 新的追蹤中繼資料頁籤,包含瀏覽器詳細資訊
  • 快照現在有 URL 列

image

HTML Report Update

  • HTML 報告現在支援動態篩選
  • 報告現在是單一靜態 HTML 檔案,可以透過電子郵件或作為 slack 附件傳送。

image

Ubuntu ARM64 支援與更多功能

  • Playwright 現在支援 Ubuntu 20.04 ARM64. You 現在可以 run Playwright tests inside Docker on Apple M1 and on Raspberry Pi.

  • You 現在可以 use Playwright to install stable version of Edge on Linux:

    npx playwright install msedge

新的 API

版本 1.16

🎭 Playwright Test

API Testing

Playwright 1.16 引入新的 API 測試,讓您可以直接從 Node.js 向伺服器發送請求!現在您可以:

  • test your server API
  • prepare server side state before visiting the web application in a test
  • validate server side post-conditions after running some actions in the browser

To do a request on behalf of Playwright's Page, use new page.request API:

import { test, expect } from '@playwright/test';

test('context fetch', async ({ page }) => {
// Do a GET request on behalf of page
const response = await page.request.get('http://example.com/foo.json');
// ...
});

To do a stand-alone request from node.js to an API endpoint, use new request fixture:

import { test, expect } from '@playwright/test';

test('context fetch', async ({ request }) => {
// Do a GET request on behalf of page
const response = await request.get('http://example.com/foo.json');
// ...
});

在我們的 API 測試指南中閱讀更多。

Response Interception

現在可以透過結合 API 測試請求攔截來執行回應攔截。

例如,我們可以模糊頁面上的所有圖片:

import { test, expect } from '@playwright/test';
import jimp from 'jimp'; // image processing library

test('response interception', async ({ page }) => {
await page.route('**/*.jpeg', async route => {
const response = await page._request.fetch(route.request());
const image = await jimp.read(await response.body());
await image.blur(5);
await route.fulfill({
response,
body: await image.getBufferAsync('image/jpeg'),
});
});
const response = await page.goto('https://playwright.dev');
expect(response.status()).toBe(200);
});

response interception.

New HTML reporter

使用 --reporter=html 或在 playwright.config.ts 檔案中的 reporter 項目來試用新的 HTML 報告器:

$ npx playwright test --reporter=html

HTML 報告器具有關於測試及其失敗的所有資訊,包括呈現追蹤和圖片檔案。

html reporter

our reporters.

🎭 Playwright Library

locator.waitFor

等待定位器解析為具有給定狀態的單一元素。預設為 state: 'visible'

在處理清單時特別有用:

import { test, expect } from '@playwright/test';

test('context fetch', async ({ page }) => {
const completeness = page.locator('text=Success');
await completeness.waitFor();
expect(await page.screenshot()).toMatchSnapshot('screen.png');
});

locator.waitFor().

Docker support for Arm64

Playwright Docker 映像現已針對 Arm64 發佈,因此可以在 Apple Silicon 上使用。

Docker integration.

🎭 Playwright Trace Viewer

  • web-first assertions inside trace viewer
  • run trace viewer with npx playwright show-trace and drop trace files to the trace viewer PWA
  • API testing is integrated with trace viewer
  • better visual attribution of action targets

Trace Viewer.

瀏覽器版本

  • Chromium 97.0.4666.0
  • Mozilla Firefox 93.0
  • WebKit 15.4

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 94
  • Microsoft Edge 94

版本 1.15

🎭 Playwright Library

🖱️ Mouse Wheel

透過使用 mouse.wheel(),您現在可以垂直或水平滾動。

📜 新的 Headers API

以前無法取得回應的多個標頭值。現在這是可能的,並且有額外的輔助函數可用:

🌈 Forced-Colors emulation

現在可以透過在 browser.newContext() 中傳遞它或呼叫 page.emulateMedia() 來模擬 forced-colors CSS 媒體功能。

新的 API

🎭 Playwright Test

🤝 test.parallel() run tests in the same file in parallel

test.describe.parallel('group', () => {
test('runs in parallel 1', async ({ page }) => {
});
test('runs in parallel 2', async ({ page }) => {
});
});

預設情況下,單一檔案中的測試按順序執行。如果您在單一檔案中有許多獨立測試,您現在可以使用 test.describe.parallel(title, callback) 平行執行它們。

🛠 Add --debug CLI flag

透過使用 npx playwright test --debug,它將為您啟用 Playwright Inspector 來偵錯您的測試。

瀏覽器版本

  • Chromium 96.0.4641.0
  • Mozilla Firefox 92.0
  • WebKit 15.0

版本 1.14

🎭 Playwright Library

⚡️ New "strict" mode

選擇器歧義是自動化測試中的常見問題。「嚴格」模式確保您的選擇器指向單一元素,否則會拋出例外。

在您的動作呼叫中傳遞 strict: true 以啟用。

// This will throw if you have more than one button!
await page.click('button', { strict: true });

📍 新的 Locators API

Locator 代表頁面上元素的檢視。它捕獲在任何時刻擷取元素所需的邏輯。

LocatorElementHandle 之間的差異在於,後者指向特定元素,而 Locator 捕獲如何擷取該元素的邏輯。

Also, locators are "strict" by default!

const locator = page.locator('button');
await locator.click();

文件中了解更多。

🧩 Experimental ReactVue selector engines

React 和 Vue 選擇器允許透過元件名稱和/或屬性值來選擇元素。語法與屬性選擇器非常相似,並支援所有屬性選擇器運算子。

await page.locator('_react=SubmitButton[enabled=true]').click();
await page.locator('_vue=submit-button[enabled=true]').click();

react 選擇器文件vue 選擇器文件 中了解更多。

✨ New nthvisible selector engines

  • nth selector engine is equivalent to the :nth-match pseudo class, but could be combined with other selector engines.
  • visible selector engine is equivalent to the :visible pseudo class, but could be combined with other selector engines.
// select the first button among all buttons
await button.click('button >> nth=0');
// or if you are using locators, you can use first(), nth() and last()
await page.locator('button').first().click();

// click a visible button
await button.click('button >> visible=true');

🎭 Playwright Test

✅ Web-First Assertions

expect 現在支援lots of new web-first assertions.

請考慮以下範例:

await expect(page.locator('.status')).toHaveText('Submitted');

Playwright Test 會重複測試具有選擇器 .status 的節點,直到取得的節點具有 "Submitted" 文字為止。它會不斷重新取得節點並檢查,直到滿足條件或達到逾時為止。您可以傳遞此逾時或透過測試配置中的 testProject.expect 值一次性配置它。

預設情況下,斷言的超時時間未設定,因此會無限等待,直到整個測試超時。

List of all new assertions:

⛓ Serial mode with describe.serial

宣告應始終循序執行的測試群組。如果其中一個測試失敗,則跳過所有後續測試。群組中的所有測試會一起重試。

test.describe.serial('group', () => {
test('runs first', async ({ page }) => { /* ... */ });
test('runs second', async ({ page }) => { /* ... */ });
});

文件中了解更多。

🐾 Steps API with test.step

Split long tests into multiple steps using test.step() API:

import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
await test.step('Log in', async () => {
// ...
});
await test.step('news feed', async () => {
// ...
});
});

步驟資訊在報告器 API 中公開。

🌎 Launch web server before running tests

要在測試期間啟動伺服器,請在配置檔案中使用 webServer 選項。伺服器會等待指定的 URL 可用後再執行測試,並且該 URL 會在建立情境時作為 baseURL 傳遞給 Playwright。

playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
command: 'npm run start', // command to launch
url: 'http://127.0.0.1:3000', // url to await for
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
});

文件中了解更多。

瀏覽器版本

  • Chromium 94.0.4595.0
  • Mozilla Firefox 91.0
  • WebKit 15.0

版本 1.13

Playwright Test

Playwright

工具

  • Playwright 追蹤檢視器現在顯示參數、回傳值和 console.log() 呼叫。
  • Playwright 檢查器可以產生 Playwright 測試。

新增與重新編寫的指南

瀏覽器版本

  • Chromium 93.0.4576.0
  • Mozilla Firefox 90.0
  • WebKit 14.2

新的 Playwright API

版本 1.12

⚡️ Introducing Playwright Test

Playwright Test 是 Playwright 團隊從頭開始建立的新測試執行器,專門為滿足端到端測試需求而設計:

  • 在所有瀏覽器中執行測試。
  • 並行執行測試。
  • 享受開箱即用的上下文隔離和合理預設值。
  • 在失敗時擷取影片、螢幕截圖和其他製品。
  • 將您的 POM 整合為可擴充的設備。

Installation:

npm i -D @playwright/test

Simple test tests/foo.spec.ts:

import { test, expect } from '@playwright/test';

test('basic test', async ({ page }) => {
await page.goto('https://playwright.dev/');
const name = await page.innerText('.navbar__title');
expect(name).toBe('Playwright');
});

Running:

npx playwright test

👉 在 Playwright 測試文件中閱讀更多。

🧟‍♂️ Introducing Playwright Trace Viewer

Playwright Trace Viewer 是一個新的 GUI 工具,可幫助探索在腳本執行後記錄的 Playwright 追蹤。Playwright 追蹤讓您檢查:

  • page DOM before and after each Playwright action
  • page rendering before and after each Playwright action
  • browser network during script execution

Traces are recorded using the new browserContext.tracing API:

const browser = await chromium.launch();
const context = await browser.newContext();

// Start tracing before creating / navigating a page.
await context.tracing.start({ screenshots: true, snapshots: true });

const page = await context.newPage();
await page.goto('https://playwright.dev');

// Stop tracing and export it into a zip archive.
await context.tracing.stop({ path: 'trace.zip' });

Traces are examined later with the Playwright CLI:

npx playwright show-trace trace.zip

That will open the following GUI:

image

👉 在追蹤檢視器文件中閱讀更多。

瀏覽器版本

  • Chromium 93.0.4530.0
  • Mozilla Firefox 89.0
  • WebKit 14.2

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 91
  • Microsoft Edge 91

新的 API

版本 1.11

🎥 New video: Playwright: A New Test Automation Framework for the Modern Web (slides)

  • We talked about Playwright
  • Showed engineering work behind the scenes
  • Did live demos with new features ✨
  • 特別感謝 applitools 主辦活動並邀請我們!

瀏覽器版本

  • Chromium 92.0.4498.0
  • Mozilla Firefox 89.0b6
  • WebKit 14.2

新的 API

版本 1.10

Bundled Browser Versions

  • Chromium 90.0.4430.0
  • Mozilla Firefox 87.0b10
  • WebKit 14.2

此版本也對以下穩定頻道進行了測試:

  • Google Chrome 89
  • Microsoft Edge 89

新的 API

版本 1.9

  • Playwright Inspector 是一個新的 GUI 工具,用於編寫和偵錯您的測試。
    • 逐行偵錯您的 Playwright 腳本,支援播放、暫停和逐步執行。
    • 透過錄製使用者操作編寫新腳本。
    • 透過滑鼠懸停在元素上為您的腳本產生元素選擇器
    • Set the PWDEBUG=1 environment variable to launch the Inspector
  • Pause script execution with page.pause() in headed mode. Pausing the page launches Playwright Inspector for debugging.
  • New has-text pseudo-class for CSS selectors. :has-text("example") matches any element containing "example" somewhere inside, possibly in a child or a descendant element. See more examples.
  • 頁面對話框現在自動關閉:除非配置了 dialog 事件的監聽器,否則在執行過程中會自動關閉頁面對話框。了解更多相關資訊。
  • Playwright for Python 現在穩定,具有慣用的 snake case API 和預建的 Docker 映像,可在 CI/CD 中執行測試。

瀏覽器版本

  • Chromium 90.0.4421.0
  • Mozilla Firefox 86.0b10
  • WebKit 14.1

新的 API

版本 1.8

新的 API

瀏覽器版本

  • Chromium 90.0.4392.0
  • Mozilla Firefox 85.0b5
  • WebKit 14.1

版本 1.7

  • New Java SDK: Playwright for Java is現在on par with JavaScript, Python.NET bindings.
  • Browser storage API: 新的 convenience APIs to save and load browser storage state (cookies, local storage) to simplify automation scenarios with authentication.
  • 新的 CSS 選擇器:我們聽到了您對更靈活選擇器的回饋意見,並改良了選擇器實作。Playwright 1.7 引入了新的 CSS 擴充功能,更多功能即將推出。
  • 新網站playwright.dev 的文件網站已更新,現在使用 Docusaurus 建置。
  • 支援Apple Silicon:WebKit 和 Chromium 的 Playwright 瀏覽器二進位檔現在為 Apple Silicon 建置。

新的 API

瀏覽器版本

  • Chromium 89.0.4344.0
  • Mozilla Firefox 84.0b9
  • WebKit 14.1