0
0
Cypresstesting~15 mins

cy.readFile() assertions in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify contents of a JSON file using cy.readFile()
Preconditions (2)
Step 1: Use cy.readFile() to read 'cypress/fixtures/userData.json'
Step 2: Assert that the 'name' field equals 'Alice'
Step 3: Assert that the 'email' field contains '@example.com'
Step 4: Assert that the 'age' field is a number greater than 18
✅ Expected Result: The test passes if all assertions on the JSON file content are true
Automation Requirements - Cypress
Assertions Needed:
Assert exact match for 'name' field
Assert substring presence in 'email' field
Assert numeric and range condition for 'age' field
Best Practices:
Use cy.readFile() with correct relative path
Chain assertions properly with .then() or directly
Use clear and descriptive assertion messages
Avoid hardcoding file content in test, rely on fixture file
Automated Solution
Cypress
describe('Verify JSON file contents with cy.readFile()', () => {
  it('should read userData.json and assert fields', () => {
    cy.readFile('cypress/fixtures/userData.json').then((data) => {
      expect(data).to.have.property('name', 'Alice')
      expect(data.email).to.include('@example.com')
      expect(data.age).to.be.a('number').and.to.be.greaterThan(18)
    })
  })
})

This test suite reads the JSON file using cy.readFile() with the correct relative path to the fixture file.

Inside the then callback, it asserts the name property exactly matches 'Alice'.

It checks the email field contains the substring '@example.com' to verify a valid email domain.

Finally, it asserts the age is a number and greater than 18, ensuring the user is an adult.

This approach uses Cypress best practices by chaining assertions inside the promise callback and avoiding hardcoded data in the test code.

Common Mistakes - 4 Pitfalls
{'mistake': 'Using incorrect file path in cy.readFile()', 'why_bad': 'The test will fail because the file cannot be found, causing a file not found error.', 'correct_approach': "Use the correct relative path from the project root, e.g., 'cypress/fixtures/userData.json'."}
Trying to assert on cy.readFile() directly without .then()
Hardcoding expected file content inside the test instead of reading from fixture
Using loose assertions like expect(data.name).to.exist without checking value
Bonus Challenge

Now add data-driven testing to verify three different JSON files with different user data

Show Hint