赛普拉斯的定制find命令

问题描述 投票:0回答:1

我有一个让我我的元素与data-cy属性自定义命令。

Cypress.Commands.add("getById", (id) => {
    cy.get(`[data-cy=${id}]`)
})

一切都工作正常。

现在,如果我有发现同样这将是很好。它会看起来像这样:

Cypress.Commands.add("findById", { prevSubject: true }, (subject, id) => {
    cy.wrap(subject).find(`[data-cy=${id}]`)
})

这个问题存在着柏树引发错误使用此代码:

cy.root().then((root) => {
    if(root.findById("...").length) {
     ...
   }
})

该错误是"root.findById" is not a function

你能不能帮我正确编写自定义命令?

testing cypress
1个回答
0
投票

最根本的问题是,subject到命令已经被包裹传递,所以只是从连锁它find()。还需要返回结果在测试中使用它。

自定义命令

Cypress.Commands.add("findById", { prevSubject: true }, (subject, id) => {
  return subject.find(`[data-cy=${id}]`)
})

接下来的问题是,你不能混用“普通”与Cypress的js代码的命令,所以返回的值必须从.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用于测试试验(应用程序/发现逐id.html)

<div>
  <div data-cy="1"></div>
  <div data-cy="2"></div>
  <div data-cy="2"></div>
  <div data-cy="3"></div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.