12

I would like to check that a file is downloaded as part of my test. I only need to confirm that the file is downloaded after clicking a button. I have no need to read the file and its contents. All the files I am downloading are zips, not sure if that makes them harder to read?

it('Initiate download', () => {
  cy.get('[id="download-button"]')
    .should('be.visible')
    .click()
 });

 it('Verify the downloaded file', () => {
   cy.readFile('/Downloads/fileName.zip')
     .should('exist')
 });
Finney14
  • 151
  • 1
  • 2
  • 8
  • https://stackoverflow.com/questions/47930881/how-can-i-use-cypress-io-to-assert-that-a-file-download-has-been-initiated-witho – Tom1425 Mar 04 '21 at 22:41

2 Answers2

21

You can try this

const path = require("path");

it('Verify the downloaded file', () => {
   const downloadsFolder = Cypress.config("downloadsFolder");
   cy.readFile(path.join(downloadsFolder, "fileName.zip")).should("exist");
});
Husnul Aman
  • 379
  • 1
  • 9
  • 1
    Why isn't this answer accepted yet, @Finney14? – Derek Henderson Oct 06 '21 at 14:38
  • Be aware of [this issue](https://github.com/cypress-io/cypress/issues/14857) though... – Marc-André Lafortune Dec 22 '21 at 23:28
  • Some other approaches like [this](https://stackoverflow.com/a/62787541/1175496) and [this](https://docs.cypress.io/api/commands/task#Read-a-file-that-might-not-exist) use `cy.task(...)`, because they use node modules like `fs.existsSync(...)`. This answer is elegant because it uses `cy.readFile(...)`; it doesn't need `cy.task(...)` so it's short and easy. However, for me, the downloaded file is a large PDF, and so `readFile` (or logging the file contents to cy log as part of the assertion) *slowed down my test*, maybe I should use `{log: false}`. Or use "exists" approach instead of "read" – The Red Pea Jan 21 '22 at 05:24
0

I also ran into the same issue but got resolved by using a double backslash for the download folder path and this resolved my issue

it('Verify the downloaded file', () => {
   cy.readFile('cypress\\Downloads\\fileName.zip')
   .should('exist')
 });
shreyas
  • 27
  • 1
  • 9