隔离性
什么是测试隔离?
测试隔离指的是每个测试完全独立于其他测试。每个测试都独立运行,不依赖于其他测试。这意味着每个测试都有自己的本地存储、会话存储、cookies 等。Playwright 通过浏览器上下文来实现这一点,这些上下文类似于隐身模式的个人资料。它们创建速度快且成本低,完全隔离,即使在同一个浏览器中运行。Playwright 为每个测试创建一个上下文,并在该上下文中提供一个默认的页面。
测试隔离的两种方式
测试隔离有两种不同的策略:从头开始或在测试之间进行清理。中间清理的缺点是,可能会忘记清理,并且有些内容(如 “已访问的链接”)是无法清理的。一个测试的状态可能会泄漏到下一个测试,导致测试失败,并使调试变得更加困难,因为问题可能来自于其他测试。从头开始意味着一切都是新的,这样如果测试失败,你只需在该测试内部调试即可。
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();