You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Playwright中通过Fixture将page.locator映射为$

问题解决:Playwright Fixture 作用域不匹配报错

错误原因

你设置的$ fixture作用域为worker,但它依赖的page是test作用域的fixture(每个测试用例/套件都会生成独立的page实例)。Playwright不允许高作用域(worker)的fixture依赖低作用域(test)的fixture——worker生命周期覆盖多个测试,无法绑定到某个特定的page实例,因此触发报错。

修复方案

将$ fixture的作用域改为test,使其和page作用域匹配,每个测试实例都会绑定对应page的locator方法:

$: [async ({ page }, use) => {
  const $ = page.locator;
  await use($);
}, { scope: 'test' }]

替代方案(直接在测试文件中定义)

如果不想用fixture,也可以在测试前置钩子中直接挂载到全局,简化调用:

test.beforeEach(async ({ page }) => {
  globalThis.$ = page.locator;
});

// 测试用例中直接使用
test('示例测试', async () => {
  await $('text=按钮').click();
});

内容的提问来源于stack exchange,提问作者Aleksandrenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 12:28:15