[英]cypress custom find command
我有一个自定义命令,可以让我使用data-cy
属性获取我的元素。
Cypress.Commands.add("getById", (id) => {
cy.get(`[data-cy=${id}]`)
})
一切正常。
现在如果我有同样的 find 就好了。 它看起来像这样:
Cypress.Commands.add("findById", { prevSubject: true }, (subject, id) => {
cy.wrap(subject).find(`[data-cy=${id}]`)
})
问题是 cypress 使用此代码引发错误:
cy.root().then((root) => {
if(root.findById("...").length) {
...
}
})
错误是"root.findById" is not a function
。
你能帮我正确编写那个自定义命令吗?
基本问题是传递给命令的subject
已经被包装,所以只需从它链接find()
。 您还需要返回结果以在测试中使用它。
自定义命令
Cypress.Commands.add("findById", { prevSubject: true }, (subject, id) => {
return subject.find(`[data-cy=${id}]`)
})
下一个问题是您不能将“普通”js 代码与 Cypress 命令混合使用,因此必须从.then()
访问返回值。
规格
describe('...', () => {
it('...', () => {
cy.visit('app/find-by-id.html')
cy.root().findById('2').then(el => {
console.log('found', el, el.length)
expect(el.length).to.eq(2)
})
})
})
用于测试测试的html(app/find-by-id.html)
<div>
<div data-cy="1"></div>
<div data-cy="2"></div>
<div data-cy="2"></div>
<div data-cy="3"></div>
</div>
添加到@Richard Matsen 的回答中,您可能希望在您的命令中添加一些日志,以便它在您的柏树日志中显示良好,就像您直接使用.find(...)
:
Cypress.Commands.add(
"findByTestId",
{
prevSubject: ["element"],
},
(
subject: Cypress.Chainable<HTMLElement>,
testId: string,
options?: Partial<
Cypress.Loggable &
Cypress.Timeoutable &
Cypress.Withinable &
Cypress.Shadow
>
) => {
const $el = subject.find(`[data-testid=${testId}]`, options);
Cypress.log({
$el: $el as any,
name: "findByTestId",
message: testId,
});
return $el;
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.