Playwright+Cucumber+JS中toMatchAriaSnapshot()调用报错求助
解决Playwright结合Cucumber使用toMatchAriaSnapshot()时的"must be called during the test"错误
问题场景
在Playwright+Cucumber+JavaScript的测试项目中,调用toMatchAriaSnapshot()断言时触发以下错误:
Error: toMatchAriaSnapshot() must be called during the test
相关代码片段:
const { expect } = require('@playwright/test'); await expect(this.taskTimeLine).toMatchAriaSnapshot(` - text: "/Modified on: \\d+:\\d+ PM Completed Task Task completed by:/" - text: Closed - button "Assign" - button "Add to Queue" - link "Open Record" - button "Delete" `);
错误日志:
Error: toMatchAriaSnapshot() must be called during the test at Object.toMatchAriaSnapshot (/Users/<>/PlaywrightProjects/<project>/node_modules/playwright/lib/matchers/toMatchAriaSnapshot.js:34:24) at Object.toMatchAriaSnapshot (/Users/<>/PlaywrightProjects/<project>/node_modules/playwright/lib/matchers/expect.js:98:30) at /Users/<>/PlaywrightProjects/<project>/node_modules/playwright/lib/common/expectBundleImpl.js:338:834 at Object.o [as 8103f153e03154d440ebdeb070612411$toMatchAriaSnapshot] (/Users/<>/PlaywrightProjects/<project>/node_modules/playwright/lib/common/expectBundleImpl.js:338:849)
原因分析
Playwright的toMatchAriaSnapshot()是测试专属断言,依赖Playwright测试运行时提供的上下文环境(包括测试生命周期、页面对象绑定等)。而原生Cucumber的步骤定义默认没有与Playwright的测试上下文关联,导致断言无法识别当前处于有效测试流程中。
解决方案
1. 正确集成Playwright与Cucumber
不要单独使用原生Cucumber,需通过Playwright的测试运行时绑定Cucumber的执行上下文:
- 确保项目中同时安装
@playwright/test和@cucumber/cucumber - 在Cucumber配置文件(如
cucumber.js)中指定测试环境,确保每个步骤都能访问Playwright上下文。
2. 在Cucumber钩子中绑定Playwright上下文
通过Cucumber的Before/After钩子初始化Playwright浏览器、上下文,并将expect和页面对象注入到步骤上下文:
const { Before, After } = require('@cucumber/cucumber'); const { chromium, expect } = require('@playwright/test'); Before(async function () { // 初始化Playwright浏览器和上下文 this.browser = await chromium.launch(); this.context = await this.browser.newContext(); this.page = await this.context.newPage(); // 将Playwright的expect绑定到当前步骤上下文 this.playwrightExpect = expect; }); After(async function () { // 清理资源 await this.page.close(); await this.context.close(); await this.browser.close(); });
3. 在步骤定义中使用绑定的expect
确保在Cucumber的步骤函数内部调用toMatchAriaSnapshot(),且使用钩子中注入的Playwright expect:
When('验证任务时间线的ARIA快照', async function () { // 确保taskTimeLine是当前页面对象中的元素定位器 const taskTimeLine = this.page.locator('#task-timeline'); await this.playwrightExpect(taskTimeLine).toMatchAriaSnapshot(` - text: "/Modified on: \\d+:\\d+ PM Completed Task Task completed by:/" - text: Closed - button "Assign" - button "Add to Queue" - link "Open Record" - button "Delete" `); });
4. 避免在非测试流程中调用断言
- 确保
toMatchAriaSnapshot()仅在Cucumber的Given/When/Then步骤函数内部执行 - 检查元素定位器
taskTimeLine是否来自当前测试的页面对象,而非外部未绑定的对象
5. 更新依赖版本
旧版本的Playwright或Cucumber可能存在集成兼容性问题,执行以下命令更新到最新稳定版:
npm update @playwright/test @cucumber/cucumber
验证
调整完成后,重新运行Cucumber测试,确认错误不再出现,toMatchAriaSnapshot()断言正常执行。
内容的提问来源于stack exchange,提问作者Nagarjun Reddy K
相关产品推荐
相关产品推荐

