Search code examples
cypresswritefile

How to write data in a file without replacing the existing data using cy.writeFile


I'm trying to save some data from API in a .json file using cy.writeFile method, but my code is replacing the existing data. What I need is to add additional data.

 cy.intercept('POST', 'http://viasphere.localhost/sites/datatable').as('response')
        cy.contains('Sortir').click()
        cy.wait('@response').get('@response').then(xhr => {
            console.log(xhr)
            let siteID = xhr.response.body.data[0].id
            let creationDate = xhr.response.body.data[0].created_at
            let RM = xhr.response.body.data[0].metal_rollout
            let clientGroup = xhr.response.body.data[0].client_contact_group

            cy.writeFile('SiteAPIdata.json', {siteID2: siteID})

After the run, the data existing inside the SiteAPIdata.json file is being replaced by the new data. The SiteAPIdata.json file is located in cypress/fixtures/ folder.

Thank you!


Solution

  • Assuming you want to append the new data to the existing data, that can easily be accomplished by using cy.readFile() before writing.

    ...
    cy.readFile('SiteAPIdata.json').then((data) => {
      data.siteID = siteID;
      cy.writeFile('SiteAPIdata.json', data);
    })