skip to Main Content

Hope someone can make sense of this
I have created commands for search on data id’s

Cypress.Commands.add('getByDataQAId', (selector, ...args) => {
    return cy.get(`[data-qa-id=${selector}]`, ...args)
})

Cypress.Commands.add('findByDataQAId', (selector, ...args) => {
    return cy.find(`[data-qa-id=${selector}]`, ...args)
})

I am now using these to search for an element on the screen, Due to how the screen is layed out and how the dev’s have created the id’s I need to use these together

cy.getByDataQAId('card-detail').filter(':visible').findByDataQAId('sub-title'),

When calling this cypress fails on the Find part saying "the subject received was "undefined""

When calling this below (which for me is the same)

cy.get('[data-qa-id="card-detail"]').filter(':visible').find('[data-qa-id="sub-title"]')

This finds the field correctly. So now I am confused on why the first fails while the second passes.

Thanks for your time

2

Answers


  1. I think it is losing the reference to the first subject at the time of the second call because you are not wrapping that.

    You could add something like:

    Cypress.Commands.add('getByDataQAId', (subject, tag) => {
       return subject
       ? cy.wrap(subject).find(`[data-qa-id='${tag}']`)
       : cy.get(`[data-qa-id='${tag}']`)
    })
    
    Login or Signup to reply.
  2. I think Nak is nearly right, but you also need to designate the custom command as a child command.

    This is indicated by the option {prevSubject:true}.

    Cypress.Commands.add('findByDataQAId', {prevSubject:true}, (subject, selector, ...args) => {
      return cy.wrap(subject).find(`[data-qa-id=${selector}]`, ...args)
    })
    

    There’s examples of child command here.

    The prevSubject accepts the following values:

    • false: (default) ignore any previous subjects: (parent command)
    • true: receives the previous subject: (child command)
    • optional: may start a chain, or use an existing chain: (dual command)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search