Search code examples
javacucumbercypresscypress-cucumber-preprocessor

An icon exists in all pages, how to code this without using repetitive code?


I have a small chat icon shown in all web pages. How to write in Cypress?

The small chat icon has class of Widget and it should be found in all pages.

I could write something like this below, but I wonder if there is any other way to get rid of repetitive should('have','Widget') although, at this point I'm not even sure if using should('have','Widget') is a correct practice but it works.

cy.get('.pageA').should('have.value', 'Widget')
cy.get('.pageB').should('have.value', 'Widget')
cy.get('.pageC').should('have.value', 'Widget')
cy.get('.pageD').should('have.value', 'Widget')

I am using Cypress with Cucumber Preprocessor.


Solution

  • If the assertions line up within a single test, you can take a data-driven approach

    ['.pageA', '.pageB', '.pageC', '.pageD'].forEach(page => {
    
      cy.get(page).should('have.value', 'Widget')
    
    })
    

    or if you want individual tests

    ['.pageA', '.pageB', '.pageC', '.pageD'].forEach(page => {
    
      it(`Page ${page} has the icon`, () => {
        cy.get(page).should('have.value', 'Widget')
      })
    
    });
    

    A more concrete example from a Cypress tutorial,

    it.only('Handles filter links', () => {
      const filters = [
        {link: 'Active', expectedLength: 3},
        {link: 'Completed', expectedLength: 1},
        {link: 'All', expectedLength: 4}
      ]
      cy.wrap(filters)
        .each(filter => {
          cy.contains(filter.link)
          .click()
    
          cy.get('.todo-list li')
          .should('have.length', filter.expectedLength)
        })
    })