0
0
Cypresstesting~5 mins

Writing to files (cy.writeFile) in Cypress

Choose your learning style9 modes available
Introduction

We write to files to save data or test results during automated tests. This helps us check if our app works correctly and keeps records.

Save test data like user info or settings for later tests.
Store logs or error messages during test runs.
Create files with test results to review after tests finish.
Write configuration files needed by the app during testing.
Syntax
Cypress
cy.writeFile(path, contents, options?)

path is the file location to write to.

contents is the data you want to save (string, object, or array).

Examples
Writes a JSON object to a file named user.json.
Cypress
cy.writeFile('cypress/fixtures/user.json', { name: 'Alice', age: 25 })
Writes a simple text string to a log file.
Cypress
cy.writeFile('logs/test-log.txt', 'Test started at 10:00 AM')
Writes an array as JSON to a file.
Cypress
cy.writeFile('data/list.txt', ['apple', 'banana', 'cherry'])
Sample Program

This test writes a user object to a JSON file and then reads it back to check if the content matches exactly.

Cypress
describe('Write to file test', () => {
  it('writes user info to a JSON file', () => {
    const user = { name: 'Bob', age: 30 };
    cy.writeFile('cypress/fixtures/bob.json', user);
    cy.readFile('cypress/fixtures/bob.json').should('deep.equal', user);
  });
});
OutputSuccess
Important Notes

File paths are relative to the project root by default.

Use cy.readFile() to verify file contents after writing.

Writing large files may slow down tests; keep files small for speed.

Summary

cy.writeFile saves data to files during tests.

It helps keep records and share data between tests.

Always verify file content with cy.readFile() after writing.