0
0
Cypresstesting~5 mins

Reading file contents in Cypress

Choose your learning style9 modes available
Introduction

Reading file contents helps you check if files have the right data during tests. It makes sure your app saves or loads files correctly.

You want to check if a downloaded file has the correct text.
You need to verify a configuration file used by your app.
You want to test if a log file contains expected messages after an action.
You want to read test data from a file to use in your tests.
Syntax
Cypress
cy.readFile('path/to/file').then((content) => {
  // use content here
})

Use a relative path from your project root or absolute path.

The content can be a string, JSON object, or buffer depending on file type.

Examples
Reads a text file and checks if it contains 'Hello'.
Cypress
cy.readFile('cypress/fixtures/example.txt').then((text) => {
  expect(text).to.include('Hello')
})
Reads a JSON file and checks if the 'name' property is 'Alice'.
Cypress
cy.readFile('cypress/fixtures/data.json').then((json) => {
  expect(json.name).to.equal('Alice')
})
Reads a log file and checks if it contains the word 'Error:'.
Cypress
cy.readFile('logs/app.log').then((log) => {
  expect(log).to.match(/Error:/)
})
Sample Program

This test reads a text file named 'greeting.txt' and checks if its content exactly matches 'Hello, Cypress!'.

Cypress
describe('Read file contents test', () => {
  it('checks text file content', () => {
    cy.readFile('cypress/fixtures/greeting.txt').then((content) => {
      expect(content).to.equal('Hello, Cypress!')
    })
  })
})
OutputSuccess
Important Notes

Make sure the file path is correct relative to your project root.

Use fixtures folder for test data files to keep tests organized.

Reading large files can slow tests; keep test files small.

Summary

Use cy.readFile() to read files during tests.

You can read text, JSON, or other file types.

Check file contents with assertions inside the then() callback.