Reputation: 123
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?
Upvotes: 9
Views: 11865
Reputation: 1
Below code is working for me while updating existing .JSON value.
cy.readFile("cypress/fixtures/credentials.json").then((data) => {
data.Username = '[email protected]'
data.Password = 'test@123'
cy.writeFile("cypress/fixtures/credentials.json", JSON.stringify(data))
})
Upvotes: 0
Reputation: 189
The fixture can be read at the top of the spec file and modified for all tests in the spec.
This way you avoid unexpected problems when using the fixture in another spec
const data = require('cypress/fixtures/dataFile.json')
data.table[0].number = 3
data.table[1].number = 4
it('tests with altered fixture', () => {
...
})
Upvotes: 10
Reputation: 387
Modify fixture data before using it.
cy.fixture('user').then((user) => {
user.firstName = 'Jane'
cy.intercept('GET', '/users/1', user).as('getUser')
})
cy.visit('/users')
cy.wait('@getUser').then(({ request }) => {
expect(request.body.firstName).to.eq('Jane')
})
From: https://docs.cypress.io/api/commands/fixture#Modifying-fixture-data-before-using-it
Upvotes: 9
Reputation: 18650
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))
})
Upvotes: 4