Home > OS >  Reading values from test fixture Cypress
Reading values from test fixture Cypress

Time:02-08

I'm new to Cypress and started playing around with fixtures.I'm trying to read values from a JSON file and then assert the values in a test.

Here is my code

it('Fixture test' ,() => {
    cy.fixture('AllNotificationStates').then(notifications => {
        for(let n in notifications) {
            cy.intercept('GET', '**/api', { fixture: 'AllNotificationStates.json' });

            cy.wrap(notifications[n])
            .should('be.an', 'object')
            .and('contain', {
                rowId: 1,
                streamId: "33e24004-04ff-4c44-8d59-c8752b0f43d7",
                notificationStatus: "Sent",
              });
        }
    });
})

What this does is assert that the properties within the JSON file match the values I expect. What I'm trying to do is read the values from the fixture file save them to an object and then assert them in my test. So for example the property rowId in the contain should not be hard coded but read from the fixture file.

Edit here is my JSON file:

[
    {
      "rowId": 1,
      "streamId": "33e24004-04ff-4c44-8d59-c8752b0f43d7",
      "notificationStatus": "Sent",
      "details": {
        "name": "Notification",
        "createdTime": "2022-02-07T11:59:15.423Z",
        "createdBy": "[email protected]",
      }
]

CodePudding user response:

You can directly replace the hardcoded values with the values from the json file like this:

it('Fixture test', () => {
  cy.fixture('AllNotificationStates').then((notifications) => {
    for (let n in notifications) {

      cy.intercept('GET', '**/api', {fixture: 'AllNotificationStates.json'})

      cy.wrap(notifications[n]).should('be.an', 'object').and('contain', {
        rowId: notifications[n].rowId,
        streamId: notifications[n].streamId,
        notificationStatus: notifications[n].notificationStatus,
      })
    }
  })
})

CodePudding user response:

You can save the fixture file to access them later in the same test.

it('Fixture test' ,() => {
    cy.fixture('AllNotificationStates').then(notifications => {
        // all your fixture checks
        }
      .as('fixtureAllNotStates')

    // some other test code
   
    cy.get('@fixtureAllNotStates').then ( () => {
       // some checks with fixture data
    });
})

You can also call the fixture in beforeEach() for it to be used across multiple it blocks. This is a good reference for doing that

  •  Tags:  
  • Related