cypress-io / cypress

Fast, easy and reliable testing for anything that runs in a browser.
https://cypress.io
MIT License
47.03k stars 3.19k forks source link

readFile() doesn't retry and fails with "Unexpected end of JSON input" after partially downloading file #26850

Closed cdlans closed 1 year ago

cdlans commented 1 year ago

Current behavior

When running an e2e test which downloads a file and then asserts the file exists using cy.readFile(filename).should('exist') the test fails with "Unexpected end of JSON input".

This seems to be due to Cypress reading the file partially, before it has been downloaded completely. If I add a cy.wait(500) between the download and the assertion, then the test passes.

Alternatively I can use cy.readFile(filename, null).should('exist') so Cypress is not trying to parse the file contents. Interestingly using cy.readFile(filename, 'binary').should('exist') did not solve the error.

Desired behavior

readFile() should retry reading the file, if it encounters an "Unexpected end of JSON input".

Test code to reproduce

cy.get('#download-json').click();
cy.readFile('download.json').should('exist');

Cypress Version

12.8.1

Node version

18.14.0

Operating System

macOS 13.3.1

Debug Logs

cy.readFile("XXX.json") failed while trying to read the file at the following path:

  /XXX/XXX.json

The following error occurred:

  > "/XXX/XXX.json: Unexpected end of JSON input"[Learn more](https://on.cypress.io/readfile)
[cypress/page-objects/base.po.ts:46:12](http://localhost/__/#)
  44 |     checkIfDownloadedFileExists(filename: string) {
  45 |         const downloadedFilename = `${this.downloadsFolder}/${filename}`;
> 46 |         cy.readFile(downloadedFilename).should('exist');
     |            ^
  47 |         // cy.readFile(downloadedFilename, null).should('exist');
  48 |     }
  49 |  
View stack trace
 Print to console
    at <unknown> (http://localhost/__cypress/runner/cypress_runner.js:136769:89)
From previous event:
    at verifyAssertions (http://localhost/__cypress/runner/cypress_runner.js:136755:154)
    at Context.readFile (http://localhost/__cypress/runner/cypress_runner.js:136826:14)
    at wrapped (http://localhost/__cypress/runner/cypress_runner.js:151174:43)
From Your Spec Code:
    at AssessmentPage.checkIfDownloadedFileExists ([webpack:///./cypress/page-objects/base.po.ts:46:11](http://localhost/__/#))
    at Context.eval ([webpack:///./cypress/e2e/assessment.cy.ts:78:27](http://localhost/__/#))


### Other

_No response_
AtofStryker commented 1 year ago

Hi @cdlans. Thank you for opening an issue. Would you be able to provide a working reproduction repository for us to see what is going on? I am wondering if we are mistakingly injecting into this file.

AtofStryker commented 1 year ago

Unfortunately we have to close this issue due to inactivity. Please comment if there is new information to provide concerning the original issue and we can reopen.