Write short way test Cypress test

Viewed 64

I am trying to write short test cypress for this test, how the best way to write it ?

describe('test', () => {
    it('test 1', () => {
        cy.get('[data-cy=edit]').first().click()
        cy.get('[data-cy=t-input]').clear().type('123123123123123')
        cy.get('[data-cy=s-button]').click()
        cy.get('[data-cy=popup]').should('be.visible')
      })
    
      it('test2', () => {
        cy.get('[data-cy=edit]').first().click()
        cy.get('[data-cy=t-input]').clear().type('1231231231231216')
        cy.get('[data-cy=s-button]').click()
        cy.get('[data-cy=c-div]').find('div')
          .should('have.class', 'error')
          .and('exist')
      })
})
2 Answers

You can create custom commands and write the repeated lines there. From your test I could see these three lines being repeated, you can add these under custom command:

cy.get('[data-cy=edit]').first().click()
cy.get('[data-cy=t-input]').clear().type('123123123123123')
cy.get('[data-cy=s-button]').click()

Go to cypress/support/commands.js and write:

Cypress.Commands.add('addCardDetails', (cardNumber) => {
    cy.get('[data-cy=edit]').first().click()
    cy.get('[data-cy=t-input]').clear().type(cardNumber)
    cy.get('[data-cy=s-button]').click()
})

And in your tests you can just write:

cy.addCardDetails('123123123123123')

So Now your tests will look like:

describe('test', () => {
    it('test 1', () => {
        cy.addCardDetails('123123123123123')
        cy.get('[data-cy=popup]').should('be.visible')
    })
  
    it('test2', () => {
        cy.addCardDetails('1231231231231216')
        cy.get('[data-cy=c-div]').find('div').should('have.class', 'error').and('exist')
    })
})

If you only need this logic inside a single JS file, it's easier to create a simple JavaScript function to extract the common logic.

So your tests will look like:

    describe('test', () => {

        function addCardDetails(cardNumber) {
            cy.get('[data-cy=edit]').first().click()
            cy.get('[data-cy=t-input]').clear().type(cardNumber)
            cy.get('[data-cy=s-button]').click()
        })
    
        it('test 1', () => {
            addCardDetails('123123123123123')
            cy.get('[data-cy=popup]').should('be.visible')
        })
      
        it('test2', () => {
            addCardDetails('1231231231231216')
            cy.get('[data-cy=c-div]').find('div').should('have.class', 'error').and('exist')
        })
    })

Cypress docs recommends using a function instead of a custom command whenever possible.

Related