Home > Enterprise >  How to create an array forEach of the playlist card ids on HTML landing page and assert order via Cy
How to create an array forEach of the playlist card ids on HTML landing page and assert order via Cy

Time:12-03

HTML source:

How to create an array forEach of the playlist card ids and test to assert array positioning/order on the page ex. 0=130, 1=100 etc. in Cypress

I think I could use this slector, but unsure how create forEach array for it...

data-object-type="playlists"

Test


it('verify expected order on program landing page', () =\> {

    cy.visit(learnerLandingPage);

});

I only tried asserting against the number of playlist cards present which work as expected, but unsure how/if I can use the playlists data-object-type

  cy.get('[data-object-type="playlists"]').should('have.length', 3);

Looking for the cleaneast way to accomplish with also being able to work across different environments where the ids in array will be different

CodePudding user response:

The cleanest way is using cy.each()

const order = ['130', '100' , '1']

cy.get('[data-object-type="playlists"]').each(($el, index) => {
  expect($el.attr('data-object-id')).to.eq(order[index])
})

where $el.attr('data-object-id') uses jQuery to extract the id attribute.


An equivalent using .invoke() would be

const order = ['130', '100' , '1']

cy.get('[data-object-type="playlists"]').each(($el, index) => {
  cy.wrap($el)
    .invoke('attr', 'data-object-id')
    .should('eq', order[index])
})

This has the advantage that .should() uses retry if the table is loaded asynchronously.

CodePudding user response:

Cypress comes bundled with lodash so you can use the _.map() util to get only the values of each data-object-type.

The data-object-type should be unique and stable across environments. You will only need to know the expected values of each.

Here is a working example.

const expectedOrder = ["130", "100", "1"];
cy.get("[data-object-type]")
  .should("have.length", 3)
  // get array of data-object-type attr
  .then(($list) =>
    Cypress._.map($list, ($el) => $el.getAttribute("data-object-type"))
  )
  .should("deep.equal", expectedOrder);
  • Related