top of page
Search

Read and Write Files in Cypress

To read and write files in cypress use the following commands,



cy.writeFile('FileName.ext','text')
cy.readFile('Filename.ext').then(function(value){
    cy.log(value)
})

Write Command:


Once write command is executed, you can see the file has been created in specified path with the text.



cy.writeFile('sample.txt','Thank you!',{flag:'a+'})


If you are trying to add text to the same file, it will create a file with only the text in second command. In order to append your new text with existing text, you need to pass the flag with 'a+'. That helps us to append the text in existing file.


Read Command:

Read command will help us to read the data from text or json file. Yo can use then function to manipulate the data you read from the file.


To use json file data, you can be more specific with the values.


data in sample.json:


You can access this data by,


cy.readFile('samplej.json').then(function(temp){
     cy.log(temp.name)
     cy.log(temp.email)
 })

Code:

describe('testingreadAndWrite',()=>{
 it('testing write',()=>{
 cy.writeFile('sample.txt','Hello world!\n')
 cy.writeFile('sample.txt','Thank you!',{flag:'a+'})
 cy.writeFile('samplej.json',{name:'coderscamp',email:'coderscampindia@gmail.com'})
    })

 it('read testing',()=>{
 cy.readFile('sample.txt').then(function(value){
 cy.log(value)
        })
 cy.readFile('samplej.json').then(function(temp){
 cy.log(temp.name)
 cy.log(temp.email)
        })

    })
})

In this article you have learnt how to read and write files in cypress. Stay connected! Happy Testing!!

276 views0 comments

Recent Posts

See All

Minimum Deletions to Make Character Frequencies Unique

A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The f

Smallest String With A Given Numeric Value

The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.

bottom of page