隔離
簡介
使用 Playwright 編寫的測試會在稱為瀏覽器內容的隔離的全新環境中執行。這種隔離模型提高了再現性並防止了級聯測試失敗。
什麼是測試隔離?
測試隔離是指每個測試都與另一個測試完全隔離。每個測試都獨立於任何其他測試運行。這表示每個測試都有自己的本機儲存、會話儲存、Cookie 等。Playwright 使用 BrowserContext 來實現此目的,這相當於類似無痕模式的設定檔。它們快速且廉價地建立,並且完全隔離,即使在單一瀏覽器中運行也是如此。Playwright 為每個測試建立一個內容,並在該內容中提供預設的 Page。
為什麼測試隔離很重要?
- 沒有失敗轉移。如果一個測試失敗,它不會影響其他測試。
- 易於偵錯錯誤或不穩定性,因為您可以根據需要多次運行單個測試。
- 在平行、分片等運行時,不必考慮順序。
測試隔離的兩種方式
關於測試隔離,有兩種不同的策略:從頭開始或在測試之間清理。在測試之間清理的問題是,可能很容易忘記清理,而且有些東西是不可能清理的,例如「造訪過的連結」。來自一個測試的狀態可能會洩漏到下一個測試中,這可能會導致您的測試失敗,並使偵錯更加困難,因為問題來自另一個測試。從頭開始意味著一切都是新的,因此如果測試失敗,您只需查看該測試即可進行偵錯。
Playwright 如何實現測試隔離
Playwright 使用瀏覽器內容來實現測試隔離。每個測試都有自己的瀏覽器內容。每次運行測試都會建立一個新的瀏覽器內容。當使用 Playwright 作為測試運行器時,預設會建立瀏覽器內容。否則,您可以手動建立瀏覽器內容。
- 測試
- 函式庫
import { test } from '@playwright/test';
test('example test', async ({ page, context }) => {
// "context" is an isolated BrowserContext, created for this specific test.
// "page" belongs to this context.
});
test('another test', async ({ page, context }) => {
// "context" and "page" in this second test are completely
// isolated from the first test.
});
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
瀏覽器內容還可用於模擬涉及行動裝置、權限、地區設定和色彩配置的多頁場景。請查看我們的模擬指南以了解更多詳細資訊。
單一測試中的多個內容
Playwright 可以在單一場景中建立多個瀏覽器內容。當您想要測試多使用者功能(例如聊天)時,這非常有用。
- 測試
- 函式庫
import { test } from '@playwright/test';
test('admin and user', async ({ browser }) => {
// Create two isolated browser contexts
const adminContext = await browser.newContext();
const userContext = await browser.newContext();
// Create pages and interact with contexts independently
const adminPage = await adminContext.newPage();
const userPage = await userContext.newPage();
});
const { chromium } = require('playwright');
// Create a Chromium browser instance
const browser = await chromium.launch();
// Create two isolated browser contexts
const userContext = await browser.newContext();
const adminContext = await browser.newContext();
// Create pages and interact with contexts independently
const adminPage = await adminContext.newPage();
const userPage = await userContext.newPage();