隔离
介绍
使用 Playwright 编写的测试在称为浏览器上下文的隔离的全新环境中执行。这种隔离模型提高了可重现性并防止了级联测试失败。
什么是测试隔离?
测试隔离是指每个测试与其他测试完全隔离。每个测试都独立于任何其他测试运行。这意味着每个测试都有自己的本地存储、会话存储、cookies 等。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();