Write user data to a JSON file using Cypress
Preconditions (2)
✅ Expected Result: The file 'cypress/fixtures/user.json' contains the exact JSON object with the user details written by the test
describe('Write to file test', () => { it('writes user data to a JSON file', () => { const userData = { name: 'Alice', email: 'alice@example.com' }; // Write the userData object to a JSON file cy.writeFile('cypress/fixtures/user.json', userData); // Verify the file content matches userData cy.readFile('cypress/fixtures/user.json').should('deep.equal', userData); }); });
This test defines a simple user data object with name and email.
It uses cy.writeFile to write this object to cypress/fixtures/user.json. Passing the object directly lets Cypress handle JSON formatting.
Then, cy.readFile reads the file back and asserts that its content deeply equals the original object. This confirms the write was successful and accurate.
Using relative paths keeps the test portable. Assertions ensure the test fails if writing or reading is incorrect.
Now add data-driven testing to write three different user objects to separate JSON files
cy.writeFile() in Cypress testing?cy.writeFile() is used to save or write data into a file during Cypress tests.cy.readFile() reads data, but cy.writeFile() writes data. Deleting or opening files is not its purpose.cy.writeFile()?cy.writeFile() takes the file path as first argument and the content as second argument, which can be a string.cy.writeFile('data.json', { name: 'Alice', age: 30 })
cy.readFile('data.json').then((content) => {
console.log(content.age)
})content.age, which is 30.cy.writeFile('user.json', '{"name": "Bob", "age": 25}')cy.writeFile(). Which code snippet correctly appends the text without overwriting the file?{ flag: 'a+' } to append instead of overwrite.Pass the test and this pattern moves unknown