Cypress Write Data into JSON File

Profile picture for user arilio666

With the cypress writeFile command, we can write to a file with the specified contents.

Syntax:

cy.writeFile(filePath, contents)
cy.writeFile(filePath, contents, encoding)
cy.writeFile(filePath, contents, options)
cy.writeFile(filePath, contents, encoding, options)

Arguments Used In WriteFile:

filePath: Path to the file within the project root.
Contents: It can be a string, array, object, or even buffer.
Encoding: Encoding is followed while writing a file. This can be,

  1. 'ascii'
  2. 'base64'
  3. binary'
  4. 'hex'
  5. 'latin1'
  6. 'utf8'
  7. 'utf-8'
  8. 'ucs2'
  9. 'ucs-2'
  10. 'utf16le'
  11. 'utf-16le'
  12. null

Null allows us to write a buffer directly.

Options:

Log: Displays commands in the command log.
Flag: File system flag.
Encoding: utf8 is the default.
Timeout: Time to wait for .writeFile.

Write Data Into JSON:

  • Using writeFile(), we can write data in a JSON file.
  • We can also retrieve the data using readFile().

Example:

cy.writeFile("name.json", { "data" });

Let us write some data into a JSON using writeFile().

cy.writeFile("NarutoBio.json",{name:"Naruto",clan:"Uzumaki",occupation:"Hokage"})

We can see it has created a JSON file with the name we specified in the project root.

Let us try to verify the file.

cy.readFile('D:/iVagus/Cypress/CYPRESS-TESTING-PROJECT/NarutoBio.json').then(Naru => {
   expect(Naru.name).to.eq("Naruto")
   expect(Naru.spouse).to.eq("Hinata")
cy.log(Naru.occupation)  
 })

We can see that the file we wrote exists and can be verified using the readFile.