test cases permutation in test suite - how to avoid repetitive codes for same steps

Viewed 100

Is there a way to permutate test cases with different values in cypress in a quicker way instead of keeping copy-paste the same line of code over and over?

the example below, how to avoid repeating the "long steps of click abcd" at every test case?
Test Suite to select items.
Test Case 1: long steps of click abcd, select 1a,2a
Test Case 2: long steps of click abcd, select 1a,2b
Test Case 3: long steps of click abcd, select 1b,2a
Test Case 4: long steps of click abcd, select 1b,2b
2 Answers

You can use cypress custom commands for this:

Go to cypress/support/commands.js and write all your repetitive steps and pass the different parameters as per your use case. Below is the example of Clicking link containing text:

Cypress.Commands.add('clickLink', (label) => {
  cy.get('a').contains(label).click()
})

In your test-

cy.clickLink('Login')
cy.clickLink('Logout')

With the same custom command, we can click the 'Login' and 'Logout' buttons, just by changing the 'label' value with parameters.

Try abstracting the long step to a function

const doLongSteps = (p1, p2) => {
  // long steps of click abcd
}

it(..., () => {
  doLongSteps(1a,2a)
  expect(...
})

it(..., () => {
  doLongSteps(1a,2b)
  expect(...
})

or a data-driven approach

const data = [[1a,2a], [1a,2b], [1b,2a], [1b,2b]]

data.forEach(params => {

  it(`tests params ${params}`, () => {
    const [p1, p2] = params   // destructure individual params
    // long steps of click abcd
  })
})
Related