[英]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.