How to update a fixture file in Cypress

Viewed 5229

I have a fixture file in cypress which has json data within it

I want to be able to update the fields in this fixture file when I run the test script

For example the fixture file would read

 {
  table: [
    {
      name: 'Joe',
      number: 1,
    },
    {
      name: 'Bob',
      number: 2,
    },
  ],
};

And I want to update the number fields to 3 and 4

I have tried

cy.fixture('dataFile.json')
  .as('data')
  .then((data) => {
    data.table[0].number = 3;
    data.table[1].number = 4;
  });

but it is not working when I run the test i am still seeing everything behave as if the number fields are still 1 and 2. If I print the fields to the console i can see they are actually updated but cypress is still running with the original data

I am still new to both cypress and javascript. How can I get around this?

1 Answers

You have to use both cy.readFile() and cy.writeFile() to achieve this. You can write something like:

cy.readFile("cypress/fixtures/dataFile.json", (err, data) => {
    if (err) {
        return console.error(err);
    };
}).then((data) => {
    data.table[0].number = 3
    data.table[1].number = 4
    cy.writeFile("cypress/fixtures/dataFile.json", JSON.stringify(data))
})
Related