cpoDesign
cpoDesign

Reputation: 9153

Cypress & BDD how to pass value between two test cases?

I am using cypress with BDD syntax (https://docs.cypress.io/api/cypress-api/spec) with test cases below. (This is work in progress)

I want to pass a value of the row from "Then" row into "And" row.

Scenario: Table contains correct data
    Given I am on page "status overview"
    Then the "1" row "ID" should display "1"
      And "items" column should display "1"
      And "cost" column should display "2"
    Then the "2" row "ID" should display "1"
      And "items" column should display "1"
      And "cost" column should display "2"

My test definitions steps

Then('the {string} row {string} should display {string}', (index, column, value) => {
  column = column.toLowerCase();

  cy.task('setRowId',index);
  getRow(index)
    .find(`[data-testid="${column}"]`)
    .should('have.text', value)
})


And('{string} column should display {string}',(column, value)=>{
  column = column.toLowerCase();
  var index = (cy.task('getRowId')).toString();
  // index should be loaded with correct id from previous test
  getRow(index)
    .find(`[data-testid="${column}"]`)
    .should('have.text', value)
})

then I have added the custom cypress steps

Cypress.Commands.add('setRowId',(val) => { return (rowId = val); })

Cypress.Commands.add('getRowId',() => { return rowId; })

Upvotes: 0

Views: 1478

Answers (2)

Fody
Fody

Reputation: 32148

I think you want an alias

Then('the {string} row {string} should display {string}', (index, column, value) => {
  column = column.toLowerCase();

  cy.wrap(index).as('rowId')
  getRow(index)
    .find(`[data-testid="${column}"]`)
    .should('have.text', value)
})


And('{string} column should display {string}',(column, value)=>{
  column = column.toLowerCase();

  cy.get('@rowId')).then(rowId => {
    // rowId should be loaded with correct id from previous test
    getRow(rowId)
      .find(`[data-testid="${column}"]`)
      .should('have.text', value)
  });
})

Upvotes: 1

aki
aki

Reputation: 86

Would creating global variables for your values work in your scenario? Something like this:

//create global variable
let rowId

Then('the {string} row {string} should display {string}', (index, column, value) => {
  column = column.toLowerCase();

  //assign value to global variable
  rowId = index
  getRow(index)
    .find(`[data-testid="${column}"]`)
    .should('have.text', value)
})


And('{string} column should display {string}',(column, value)=>{
  column = column.toLowerCase()
  // assign value of global variable to index or use the global vriable itself
  index = rowId
  getRow(index)
    .find(`[data-testid="${column}"]`)
    .should('have.text', value)
})

Upvotes: 0

Related Questions