Cypress Read JSON File

Profile picture for user arilio666

You can use the cy.readFile command to read a JSON file in Cypress. Reading a JSON file is a common task to load test data into the test suite. 

This can be useful when testing your application's behavior with different data sets.

Syntax:

cy.readFile('path/to/file.json').then((json) => {
 // do something with the JSON object
});
  • In this example, the cy.readFile command reads the content of the specified JSON file and returns a promise that resolves to the parsed JSON object. 
  • The resolved object can then be used in your tests.

1.) Simple JSON Read

Let us create a simple profile.json in our fixtures folder.

{
 "id": 8739,
 "name": "Itachi",
 "clan": "Uchiha",
 "status":"dead"
}

Using the readfile command, we can fetch the contents of the JSON and assert and play around with them.

cy.readFile('cypress/fixtures/profile.json').then(Shinobi => {
   expect(Shinobi.name).to.eq("Itachi")
   expect(Shinobi.status).to.eq("dead")
   expect(Shinobi.clan).to.eq("Uchiha")
 
 })


 or
 
We can say fixture, and no need to pass the json filepath.

cy.fixture('profile').then(Shinobi => {
   expect(Shinobi.name).to.eq("Itachi")
   expect(Shinobi.status).to.eq("dead")
   expect(Shinobi.clan).to.eq("Uchiha")
 
 })
 


It does not even necessary to use objectname.attribute notation, we can use bracket notation, which will do the same thing.

cy.readFile('cypress/fixtures/profile.json').then(Shinobi => {
   expect(Shinobi['name']).to.eq("Itachi")
   expect(Shinobi['status']).to.eq("dead")
   expect(Shinobi['clan']).to.eq("Uchiha")
 
 })
 


2.) Array

Let us add another item with a list formatted as an array in the same JSON file.

{
 "id": 8739,
 "name": "Itachi",
 "clan": "Uchiha",
 "status":"dead",
 "abilities": ["infinite tsukoyomi", "Amaterasu", "mangekyu sharingan"]
}

Using the index of the Array, we can access the abilities object.

cy.readFile('cypress/fixtures/profile.json').then(Shinobi => {
   cy.log(Shinobi.abilities[0])
   cy.log(Shinobi.abilities[1])
   cy.log(Shinobi.abilities[2])
 
 })

We can see here using the index of the array list. We can access the values.

Conclusion:

This is how we can read JSON files in Cypress.