Playwright如何为所有测试统一配置Mock响应或全局beforeEach?
Playwright 全局统一配置 Mock 响应的方法
当然可以实现全局统一配置 Mock,不用在每个测试文件重复编写 page.route 代码,以下是几种实用方案:
1. 使用全局 Setup 脚本
创建全局初始化脚本,在所有测试启动前完成 Mock 配置,所有测试上下文都会继承该配置:
创建 global.setup.js 文件:
const { test: setup } = require('@playwright/test'); setup('全局 Mock 初始化', async ({ browser }) => { // 创建上下文并配置全局路由 Mock const context = await browser.newContext(); await context.route('https://dog.ceo/api/breeds/list/all', async route => { const json = { message: { 'test_breed': [] } }; await route.fulfill({ json }); }); // 保存上下文状态供后续测试使用 await context.storageState({ path: 'globalStorageState.json' }); await context.close(); });
在 playwright.config.js 中指定该脚本:
module.exports = { globalSetup: './global.setup.js', use: { storageState: 'globalStorageState.json', }, };
2. 直接在配置文件中通过 use.setup 配置
无需单独脚本,直接在配置文件的 use 字段中添加初始化逻辑,每个测试上下文创建时都会执行:
module.exports = { use: { async setup({ page }) { // 为当前上下文的所有页面配置 Mock await page.context().route('https://dog.ceo/api/breeds/list/all', async route => { const json = { message: { 'test_breed': [] } }; await route.fulfill({ json }); }); } }, };
3. 自定义全局 Fixture
如果需要更灵活的控制逻辑,可以创建带全局 Mock 的自定义 fixture:
创建 fixtures.js 文件:
const { test: base } = require('@playwright/test'); // 扩展基础测试,添加全局 Mock 逻辑 const test = base.extend({ page: async ({ page }, use) => { await page.route('https://dog.ceo/api/breeds/list/all', async route => { const json = { message: { 'test_breed': [] } }; await route.fulfill({ json }); }); await use(page); }, }); module.exports = { test };
测试文件中直接导入自定义的 test 即可:
const { test } = require('./fixtures'); test('验证全局 Mock 生效', async ({ page }) => { await page.goto('/your-test-page'); // 此时请求目标接口会自动触发 Mock 响应 });
内容的提问来源于stack exchange,提问作者No Idea For Name
相关产品推荐
相关产品推荐

