When testing file uploads and downloads, why do we validate the file content and not just the file name?
Think about what really matters to the user when uploading or downloading a file.
File names can be changed or spoofed easily. Validating the content ensures the file data is exactly what is expected, which is critical for correctness.
Consider this Cypress test snippet that downloads a file and checks its content. What will be the test result?
cy.readFile('cypress/downloads/report.txt').then((content) => { expect(content).to.include('Report Summary'); });
What does the expect assertion check?
The test reads the file content and asserts it includes the string 'Report Summary'. If true, the test passes; otherwise, it fails.
You want to check that the uploaded file contains the text 'Hello World'. Which assertion is correct?
cy.get('input[type=file]').attachFile('hello.txt'); cy.readFile('cypress/fixtures/hello.txt').then((content) => { // Which assertion here? });
Consider partial vs exact match for file content.
Using include checks if the file content contains the string anywhere, which is safer than exact match for text files.
Review this test code snippet. Why does it fail?
cy.downloadFile('https://example.com/report.pdf', 'cypress/downloads', 'report.pdf'); cy.readFile('cypress/downloads/report.pdf').then((content) => { expect(content).to.include('PDF-1.4'); });
Think about file types and how readFile works.
readFile reads files as text by default. PDFs are binary files, so reading as text can corrupt content and cause assertion to fail.
Which approach best ensures reliable validation of file downloads in Cypress tests across different browsers?
Consider how browsers handle downloads differently and how Cypress can control network requests.
Intercepting the download request allows Cypress to save the file in a controlled location and validate content reliably, avoiding browser-specific download folder issues.