We use cy.readFile() to check the contents of a file during tests. This helps us make sure the file has the right data.
0
0
cy.readFile() assertions in Cypress
Introduction
To verify a downloaded file contains expected text or data.
To check if a configuration file has correct settings after an action.
To confirm a log file includes specific messages after running a test.
To ensure a saved report file matches the expected format and content.
Syntax
Cypress
cy.readFile('path/to/file').should('include', 'expected text')
The path/to/file is relative to the project root.
You can use different assertions like include, equal, or contain to check file content.
Examples
This checks if the file
sample.txt contains the text 'Hello World'.Cypress
cy.readFile('cypress/fixtures/sample.txt').should('include', 'Hello World')
This verifies the JSON file exactly matches the given object.
Cypress
cy.readFile('data/config.json').should('deep.equal', { theme: 'dark', version: 1 })
This asserts the log file contains the word 'Error' anywhere inside.
Cypress
cy.readFile('logs/app.log').should('contain', 'Error')
Sample Program
This test reads the file greeting.txt and checks if it includes the word 'Welcome'.
Cypress
describe('File content test', () => { it('checks if the file contains expected text', () => { cy.readFile('cypress/fixtures/greeting.txt').should('include', 'Welcome') }) })
OutputSuccess
Important Notes
Make sure the file path is correct and the file exists before running the test.
Use should assertions to wait for the file read to complete before checking content.
You can read JSON files and assert their structure using deep.equal.
Summary
cy.readFile() helps test file contents easily.
Use assertions like include, contain, or deep.equal to check file data.
It is useful for verifying downloads, configs, logs, and reports.