Hussain Sam
Hussain Sam

Reputation: 71

How to store json data to a variable in Cypress

I am trying to fetch the employee ID from the json file in the format as below in Cypress but its returning error as Cannot read property 'name' of null

How can I retrieve the employee id for the user name "Devin Miller" ? Please help

{
  "data": [
    {
      "role": "Software Engineer",
      "organization": "Google",
      "name": "Remi Arsenault",
      "emplyeeID":"526321",
      "project": "Stadia"
    },
    {
      "role": "Data Analyst",
      "organization": "Google",
      "emplyeeID": "526322",
      "name": "Devin Miller",
      "project": "Stadia"
    }
  ]
}

Below is my code

export function GetUserData(employeeName){     
    cy
      .fixture('users')
      .its('data')
      .then((users) => {     
        Users = users.find(user => user.name === employeeName);
      })
  }

export var Users = null;

now if I am trying to do the below then it is returning error

var employeeID = Users["Remi Arsenault"].emplyeeID

Upvotes: 0

Views: 1771

Answers (1)

aeischeid
aeischeid

Reputation: 576

I think you are having some bad expectations related to async vs snyc code.

Also, for accessing the fixture data you might try this instead of the .its('data) :

cy.fixture('users').then((usersJson) => {
    let foundUser = usersJson.data.find(user => user.name === 'Remi Arsenault');
    let emloyeeID = foundUser.employeeID
    ... ['whatever else you want to do can go here inside the then callback.']
});

Upvotes: 2

Related Questions