Search code examples
jsoncypressfixtures

Cypress - find nested properties in json file


I am struggling with the following situation. I create a new user via a web page, which I save to a json file. But my tests in cypress can not search 'deep' in the file.

This is how my json file looks like:

{
  "customers" : [ {
    "customerId" : "123456",
    ...
   } ],
  "error" : ""
}

And this is how I load this json file in my test:

beforeEach('Load fixture', function () {

    cy.fixture('registerNewCustomers').its('customers').as('testdata');
    }); 
    ...
    cy.get('@testdata').then((testdata) => {

            cy.get('#inputLoginID').type(testdata.customerId);

My test can not read the nested 'customerId', but if I move it one level up to "customers" level, my test is finding it and its value.

{
  "customers" : [ {
    ...
    ...
   } ],
  "error" : "",
  "customerId" : "123456",
}

Solution

  • customers (which is saved as the alias testdata) is an array, so you would need to index the array.

    If you know which customer you want, e.g to pick the 4th customer

    cy.get('#inputLoginID').type(testdata[3].customerId)  
    

    If you've just added the customer, and therefore want the last one,

    cy.get('#inputLoginID').type(testdata[testdata.length -1].customerId)