'How do I keep writing in the same JSON file within cypress?

I'm currently setting up a test scenario that allows me to create a random email, and I would like to do more series of tests and keep writing on the same JSON file instead of overwriting what I already sent to the JSON files. Meaning that I would like to use the same JSON file to save all of the emails that I created with my tests.

Does anyone knows a better way to do this?

Cypress.Commands.add("form", ()=> {
      // fill-out form

      function makeid(length) {
        var result           = '';
        var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var charactersLength = characters.length;
        for ( var i = 0; i < length; i++ ) {
           result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
     }
     const fullName = 'MockaData Testing'
     const email = makeid(6) + "@aharo.com";

     console.log(makeid(5));

    cy.get('#full_name')
      .type(fullName)
    cy.get('#company')
      .type('Testing')
    cy.get('#phone_number')
      .type('2022569878')
    cy.get('#email')
      .type(email).writeFile('cypress/fixtures/users.json', {name: fullName, email: email})
    cy.get('#password')
      .type('Abcd1234')

    // click submit
    cy.get(".app-submit-btn-text", { multiple: true }).click()
 })



Solution 1:[1]

To achieve this you have to use { flag: 'a+' } (cypress docs). This will append the contents at the end of the file instead of overwriting it.

cy.writeFile('cypress/fixtures/users.json', {name: fullName, email: email}, {flag: 'a+'})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alapan Das