Timeouts
Playwright 测试有多个可配置的超时设置,用于处理不同任务。
| 超时类型 | 默认值 | 描述 | 
|---|---|---|
| 测试超时 | 30_000 毫秒 | 每个测试的超时。 在配置中设置  在测试中覆盖  | 
| 期望超时 | 5_000 毫秒 | 每个断言的超时。 在配置中设置  在测试中覆盖  | 
测试超时
Playwright 测试对每个测试都有超时,默认是 30 秒。测试函数、fixture 设置和 beforeEach 钩子所花费的时间都计入测试超时。
当测试超时时,会产生如下错误:
example.spec.ts:3:1 › basic test ===========================
Timeout of 30000ms exceeded.另外,fixture 的销毁操作和 afterEach 钩子有一个独立的超时,这个时间和测试函数的超时一样。
beforeAll 和 afterAll 钩子的超时也适用相同的超时设置,并且它们不共享任何测试时间。
配置文件中设置测试超时
import { defineConfig } from '@playwright/test';
export default defineConfig({
  timeout: 120_000,
});API reference: 【testConfig.timeout】。
为单个测试设置超时
import { test, expect } from '@playwright/test';
test('slow test', async ({ page }) => {
  test.slow(); // Easy way to triple the default timeout
  // ...
});
test('very slow test', async ({ page }) => {
  test.setTimeout(120_000);
  // ...
});API reference: 【test.setTimeout()】 和 【test.slow()】。
从 beforeEach 钩子修改超时
import { test, expect } from '@playwright/test';
test.beforeEach(async ({ page }, testInfo) => {
  // Extend timeout for all tests running this hook by 30 seconds.
  testInfo.setTimeout(testInfo.timeout + 30_000);
});API reference: 【testInfo.setTimeout()】。
为 beforeAll/afterAll 钩子修改超时
beforeAll 和 afterAll 钩子有一个独立的超时,默认值与测试超时相同。你可以在这些钩子内调用 【testInfo.setTimeout()】 来分别设置它们的超时。
import { test, expect } from '@playwright/test';
test.beforeAll(async () => {
  // Set timeout for this hook.
  test.setTimeout(60000);
});API reference: 【testInfo.setTimeout()】。
期望超时
自动重试断言(例如 expect(locator).toHaveText())有一个单独的超时,默认是 5 秒。期望超时与测试超时无关。超时会产生如下错误:
example.spec.ts:3:1 › basic test ===========================
Error: expect(received).toHaveText(expected)
Expected string: "my text"
Received string: ""
Call log:
  - expect.toHaveText with timeout 5000ms
  - waiting for "locator('button')"全局超时
Playwright 测试支持整个测试运行的超时。这可以防止在测试出现问题时占用过多资源。默认情况下没有全局超时,但你可以在配置文件中设置一个合理的超时(例如 1 小时)。如果超时,将会产生如下错误:
Running 1000 tests using 10 workers
  514 skipped
  486 passed
  Timed out waiting 3600s for the entire test run你可以在配置文件中设置全局超时:
import { defineConfig } from '@playwright/test';
export default defineConfig({
  globalTimeout: 3_600_000, // 设置全局超时为 1 小时
});API reference: 【testConfig.globalTimeout】 。
高级:低层级超时
这些是由测试运行器预配置的低级别超时,通常不需要更改。如果你的测试不稳定,建议先检查其他方面的原因,而不是调整这些低级别超时。
| 超时类型 | 默认值 | 描述 | 
|---|---|---|
| 操作超时 | 无超时 | 每个操作的超时。 | 
| 导航超时 | 无超时 | 每个导航操作的超时。 | 
| 全局超时 | 无超时 | 整个测试运行的超时。 | 
| beforeAll/afterAll 超时 | 30_000 毫秒 | 钩子的超时。 | 
| fixture 超时 | 无超时 | 单个 fixture 的超时。 | 
夹具超时
默认情况下,fixture 的超时与测试共享。但对于慢速的 fixture(尤其是工作区范围的 fixture),最好为其设置一个单独的超时。这样,你可以保持整体测试超时较小,并为慢速 fixture 留出更多时间。
import { test as base, expect } from '@playwright/test';
const test = base.extend<{ slowFixture: string }>({
  slowFixture: [async ({}, use) => {
    // ... perform a slow operation ...
    await use('hello');
  }, { timeout: 60_000 }]
});
test('example test', async ({ slowFixture }) => {
  // ...
});API reference: 【test.extend()】。
