Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cypress custom find command

I have a custom command that gets me my elements with the data-cy attribute.

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

everything's working fine.

Now it would be nice if I had the same with find. It would be looking like this:

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

The problem there is that cypress throws an error with this code:

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

The error is "root.findById" is not a function.

Can you help me write that custom command correctly?

like image 544
sleepysimon Avatar asked Oct 17 '22 07:10

sleepysimon


1 Answers

The basic problem is that subject passed in to the command is already wrapped, so just chain the find() from it. Also you need to return the result to use it in the test.

Custom command

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

The next problem is you can't mix 'ordinary' js code with Cypress commands, so the returned value must be accessed from a .then().

Spec

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 used to test the test (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>
like image 182
Richard Matsen Avatar answered Oct 19 '22 08:10

Richard Matsen