隔离
简介
使用 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();