Playwright按顺序执行测试时出现不稳定问题求助
问题根源分析
你的测试不稳定问题核心在于全局变量page被多个测试块共享,导致测试间状态污染:
- 在
secondaryTests块中,beforeAll仅创建一次CustomPage实例,但每个测试的afterEach都会关闭该实例。当第二个测试执行beforeEach调用page.goTo时,page已经被第一个测试的afterEach关闭,自然会抛出错误。 - 交替通过/失败的现象本质是全局变量的状态未被正确隔离,偶然的执行时序或残留状态导致结果不可控。单独运行测试时无问题,是因为全局变量不会被其他测试修改,连续运行时状态残留的问题就会暴露。
修复方案
方案一:使用局部变量隔离测试资源
将page变量从全局移至每个describe块的局部作用域,并在beforeEach中创建新实例,确保每个测试使用独立的页面资源:
import {test, expect} from '@playwright/test'; import {CustomPage} from '@classes'; test.describe('primaryTest', async () => { let page: CustomPage; // 局部变量,仅当前describe可用 test.beforeEach(async ({browser}) => { page = new CustomPage(await browser.newPage()); await page.goTo("testUrl"); }); test.afterEach(async () => { await page.close(); }); test('example test', async () => { await page.commonFunc(); }); }); test.describe('secondaryTests', async () => { let page: CustomPage; // 局部变量,仅当前describe可用 test.beforeEach(async ({browser}) => { page = new CustomPage(await browser.newPage()); await page.goTo("testUrl"); }); test.afterEach(async () => { await page.close(); }); test('example test 2', async () => { await page.commonFunc(); }); test('example test 3', async () => { await page.commonFunc(); }); });
方案二:使用Playwright自定义Fixture(推荐)
这是Playwright官方推荐的测试隔离方式,通过自定义Fixture自动为每个测试创建独立的CustomPage实例,并在测试完成后自动清理:
- 创建
fixtures.ts文件:
import { test as base } from '@playwright/test'; import { CustomPage } from '@classes'; type MyFixtures = { customPage: CustomPage; }; export const test = base.extend<MyFixtures>({ customPage: async ({ browser }, use) => { const page = new CustomPage(await browser.newPage()); await page.goTo("testUrl"); await use(page); // 将实例传递给测试 await page.close(); // 测试完成后自动清理 }, });
- 测试文件中使用该Fixture:
import { test, expect } from './fixtures'; test.describe('primaryTest', async () => { test('example test', async ({ customPage }) => { await customPage.commonFunc(); }); }); test.describe('secondaryTests', async () => { test('example test 2', async ({ customPage }) => { await customPage.commonFunc(); }); test('example test 3', async ({ customPage }) => { await customPage.commonFunc(); }); });
关键注意点
- 测试隔离是自动化测试的核心原则,绝对避免使用全局变量共享测试资源,否则必然出现不稳定问题。
- 即使配置了按顺序执行,全局变量的状态残留依然会导致测试间相互影响,前一个测试的操作会修改全局变量的状态。
内容的提问来源于stack exchange,提问作者Lee McCready
相关产品推荐
相关产品推荐

