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

如何修复Cypress自定义命令中的“Syntax error, unrecognized expression”错误?

Cypress自定义命令报错:无法识别表达式 [data-test=${selector}]

我在学习Cypress时,按照教程创建自定义命令后运行测试,出现了语法错误。相关代码和错误信息如下:

自定义命令代码(commands.ts)

declare namespace Cypress {
interface Chainable {
getByData(dataTestAttribute: string): Chainable<JQuery<HTMLElement>>
}
}

Cypress.Commands.add("getByData", (selector) => {
return cy.get('[data-test=${selector}]')
})

测试用例代码(home.cy.ts)

describe('home page', () => {
beforeEach(() =>{
cy.visit('http://localhost:3000')
})

it('the h1 contains the correct text', () => {
cy.getByData('hero-heading').contains('Testing Next.js Applications with Cypress')
})

it("the features on the homepage are correct",() =>{
cy.get("dt").eq(0).contains("4 Courses")
cy.get("dt").eq(1).contains("25+ Lessons")
cy.get("dt").eq(2).contains("Free and Open Source")
})
})

错误信息

Syntax error, unrecognized expression: [data-test=${selector}]

解决方法

问题出在字符串插值的语法上:你用了单引号包裹选择器,而单引号不支持ES6模板字符串的${}插值语法,导致Cypress把${selector}当成了选择器的一部分,引发语法错误。

只需要把选择器的单引号换成反引号即可,修改后的commands.ts代码如下:

declare namespace Cypress {
interface Chainable {
getByData(dataTestAttribute: string): Chainable<JQuery<HTMLElement>>
}
}

Cypress.Commands.add("getByData", (selector) => {
return cy.get(`[data-test=${selector}]`)
})

这样${selector}会被正确解析为传入的参数值,测试就能正常运行了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 18:35:00