The answers already given are correct, and are the conventional and documented way to approach the problem.
You can also use a Proxy set() handler to automatically persist the object every time you add a property.
function persist(fileName, initial = {}) {
Cypress._myObject = { ...initial }
const handler = {
set(obj, prop, value) {
Reflect.set(...arguments)
cy.writeFile(`./cypress/fixtures/${fileName}`, Cypress._myObject, { log: false });
return true;
}
};
return new Proxy(Cypress._myObject, handler);
}
// Wrap the object
const myObject = persist('myObject.json', { name: 'fred', age: 30 })
it('test1', () => {
// Modify it, fixture file is also updated
myObject.address1 = "somewhere"
myObject.address2 = "somecity" // could be set in a 2nd test
// Check the fixture file
cy.fixture('myObject.json').then(console.log)
.should(fixture => {
expect(fixture.address1).to.eq('somewhere')
expect(fixture.address2).to.eq('somecity')
})
})
Alternatively, a custom command (requires a nesting level)
/cypress/support/index.js
Cypress.Commands.add('persist', (fileName, initial = {}) => {
Cypress._myObject = { ...initial }
const handler = {
set(obj, prop, value) {
Reflect.set(...arguments)
cy.writeFile(`./cypress/fixtures/${fileName}`, Cypress._myObject, { log: false });
return true;
}
};
return new Proxy(Cypress._myObject, handler)
})
test
it('test2', () => {
cy.persist('myObject.json', { name: 'fred', age: 30 })
.then(myObject => {
myObject.address1 = "somewhere"
myObject.address2 = "somecity"
cy.fixture('myObject.json')
.should(fixture => {
expect(fixture.address1).to.eq('somewhere')
expect(fixture.address2).to.eq('somecity')
})
})
})