Cypress how to stored input data and parse for verification

Viewed 127

I have a table form at webpage. User filled up and hit upload then result firm is displayed.

Table a input abc
Table b input 123

I want to verify the data is displayed at result page.

How do i store the value abc 123 for verification? To avoid linear coding, i do not want to rewrite those values again and to prevent if test data changed, i just need to change once.

2 Answers

You can create a json file and save it under fixtures like data.json:

{
  "tableA": {
    "name": "table a",
    "selector": "input"
    "value": "abc",
    "checkbox": "be.checked"

  },
  "tableB": {
    "name": "table b",
    "selector": "input"
    "value": 123,
    "checkbox": "not.be.checked"
  }
}

And in your tests you can write:

describe('Some page', () => {
  beforeEach(function() {
    // "this" points at the test context object
    cy.fixture('data.json').then((data) => {
      this.data = data
    })
  })

  it('has user', function() {
    expect(this.data.tableA.name).to.equal('table a')
    expect(this.data.tableA.selector).to.equal('input')
    expect(this.data.tableA.value).to.equal('abc')
    cy.get('selector').should(this.data.tableA.checkbox)
  })
})

Important Note:

If you store and access the fixture data using this test context object, make sure to use function () { ... } callbacks. Otherwise the test engine will NOT have this pointing at the test context.

To test the tables/forms, iterate the expected results.

it('tests form', () => {
  const expected = [
    [ 'a', 'abc' ],
    [ 'b', '123' ],
  ]
  expected.forEach(exp => {
    cy.get(`table#${exp[0]}`)  // construct selector
      .find('input')
      .invoke('val')
      .should('eq', exp[1])  // verify
  })
})
Related