Skip to content

cy.writeFiles runs into errors #27097

Closed

Description

@JanUrb

Current behavior

Hello,
while integrating Cypress version 12.15.0 some of our tests failed with PayloadTooLargeError: request entity too large. The problematic test cases write files around 200 - 300 kb. Cypress UI shows the error message cy.writeFile() must only be invoked from the spec or support file

Desired behavior

On Cypress 12.14.0 the same tests ran fine.

Test code to reproduce

https://github.com/JanUrb/cypress-test-writefiles-error

Cypress Version

12.15.0

Node version

v20.3.0

Operating System

macOS 13.3.1

Debug Logs

No response

Other

No response

Activity

  1. dubzzz commented on Jun 21, 2023

    @dubzzz

    I encounter exactly the same issue when bumping to 12.15.0 on Node 18.

  2. ddnexus commented on Jun 21, 2023

    @ddnexus

    Same error with version 12.15.0 (working fine with 12.14.0) but a different origin, probably related to the size of the snapshot file:

    "after all" hook: saveSnapshots for "Test ...":
         CypressError: `cy.writeFile()` must only be invoked from the spec file or support file.
    
  3. changed the title [-]cy.writeFiles [/-] [+]cy.writeFiles runs into errors[/+] on Jun 21, 2023
  4. gabor-szallas commented on Jun 21, 2023

    @gabor-szallas

    Same error, but with cy.readFile() after updating to 12.15.0

    cy.readFile() must only be invoked from the spec file or support file.

  5. mike-plummer commented on Jun 21, 2023

    @mike-plummer
    Contributor

    We're aware of the "must only be invoked from the spec file or support file" issue and are looking into it now. Until a fix is identified, tested, and released you can temporarily downgrade to Cypress v12.14.0 which does not exhibit this issue.

  6. mike-plummer commented on Jun 21, 2023

    @mike-plummer
    Contributor

    This is a duplicate of #27099 which has a slightly more targeted description of the issue so I will close this in favor of that one

  7. arundavid1987 commented on Jun 22, 2023

    @arundavid1987

    image

  8. mike-plummer commented on Jun 26, 2023

    @mike-plummer
    Contributor

    Cypress v12.16.0 has just been released with a fix for the issue with cy.task, apologies for the oversight on that bug.

    Thanks for using Cypress, everyone!

  9. bdimitrovski commented on Jun 27, 2023

    @bdimitrovski

    This is still not resolved, as we are also getting the same error:

    ss

    The bespoke code resides in a custom class, which implements the cy.writeFile() function like so:

    cy.writeFile('cypress/support/data/paymentOrders/groupOrders.json', data);

    Is there a workaround for this, or is downgrading to 12.14.0 the only option?

  10. mike-plummer commented on Jun 27, 2023

    @mike-plummer
    Contributor

    Hi @bdimitrovski , sorry you're still having issues. We addressed an issue that was causing this error in 12.16.0 but it appears you've identified one or more edge cases we missed. Are you able to share a reproduction case we can use to troubleshoot?

  11. bdimitrovski commented on Jun 27, 2023

    @bdimitrovski

    Hi @mike-plummer ,

    Thanks for the quick reply.

    Here's the repro code https://github.com/bdimitrovski/writefile-cy-issue, however, when I used the exact same function as in my real project, I could not get it to fail, it normally populates the file using cy.writeFile.

    Is there anything else I could be missing?

  12. elGatoMantocko commented on Jun 27, 2023

    @elGatoMantocko

    Still able to reproduce #27099 via cypress-localstorage-commands.

    #27099 (comment)

  13. chrisbreiding commented on Jun 28, 2023

    @chrisbreiding
    Contributor

    @elGatoMantocko Thanks for the report. That will be helpful for debugging.

  14. chrisbreiding commented on Jun 28, 2023

    @chrisbreiding
    Contributor

    Here's the repro code bdimitrovski/writefile-cy-issue, however, when I used the exact same function as in my real project, I could not get it to fail, it normally populates the file using cy.writeFile.

    Is there anything else I could be missing?

    @bdimitrovski It's tricky to say, since that's the information we'd be trying to use the reproduction to suss out. It could be something different with how the project is structured, as in which file the function that calls cy.writeFile is defined. It could a difference in how the spec code is calling it. It could be useful if you posted your cypress.config.js or as much of it as you can.

    There's two known issues that cause this error right now (and are in the process of being fixed), so I would first check to see if your project code is encountering it because of one of these:

    • The command is called with an extra argument that isn't part of its API, as in cy.writeFile('file.txt', 'contents', 'utf-8', { log: false }, { flag: 'w' }). In that case, the { flag: 'w' } object should be part of the { log: false } object.
    • The command is called with a trailing undefined argument. This usually happens when one of the arguments is a variable, like:
    function writeFile (options) {
      cy.writeFile('file.txt', 'contents', options)
    }
    
    writeFile()
  15. Jacek-fstack commented on Jun 30, 2023

    @Jacek-fstack

    I have the same issue - only showing up in headless mode
    example:

      cy.writeFile('cypress/fixtures/10Users.csv', data, (err) => {
          if (err) { cy.log(err); } else {
            cy.log('File written successfully\n');
          }
        });
    

    inside of the spec file

  16. bdimitrovski commented on Jun 30, 2023

    @bdimitrovski

    Here's the repro code bdimitrovski/writefile-cy-issue, however, when I used the exact same function as in my real project, I could not get it to fail, it normally populates the file using cy.writeFile.
    Is there anything else I could be missing?

    @bdimitrovski It's tricky to say, since that's the information we'd be trying to use the reproduction to suss out. It could be something different with how the project is structured, as in which file the function that calls cy.writeFile is defined. It could a difference in how the spec code is calling it. It could be useful if you posted your cypress.config.js or as much of it as you can.

    There's two known issues that cause this error right now (and are in the process of being fixed), so I would first check to see if your project code is encountering it because of one of these:

    • The command is called with an extra argument that isn't part of its API, as in cy.writeFile('file.txt', 'contents', 'utf-8', { log: false }, { flag: 'w' }). In that case, the { flag: 'w' } object should be part of the { log: false } object.
    • The command is called with a trailing undefined argument. This usually happens when one of the arguments is a variable, like:
    function writeFile (options) {
      cy.writeFile('file.txt', 'contents', options)
    }
    
    writeFile()

    @chrisbreiding thanks for looking into this - here' a part of my cypress.config.js file:

    const { defineConfig } = require('cypress');
    const fs = require('fs-extra');
    const path = require('path');
    
    function getConfigurationByFile(file) {
      const pathToConfigFile = path.resolve('..', 'cypress/cypress/config', `${file}.config.json`);
    
      return fs.readJson(pathToConfigFile);
    }
    
    module.exports = defineConfig({
      reporter: 'cypress-multi-reporters',
      reporterOptions: {
        configFile: 'reporter-config.json'
      },
      e2e: {
        responseTimeout: 30000,
        requestTimeout: 30000,
        viewportWidth: 1440,
        viewportHeight: 900,
        baseUrl: "http://localhost:8080/",
        supportFile: "cypress/support/e2e.js",
        video: false,
        trashAssetsBeforeRuns: true,
        env: {
          username: "**********",
          password: "**********",
          apiBaseUrl: "**********",
          docsUrl: "**********"
        },
        specPattern: "cypress/e2e/**/*.spec.ts",
        setupNodeEvents(on, config) {
          const loggerOptions = {
            outputRoot: `${config.projectRoot}/cypress/reports/logs`,
            outputTarget: {
              'verbose.log': 'txt',
              'verbose.json': 'json'
            }
          }
    
          require('cypress-mochawesome-reporter/plugin')(on);
          require('cypress-terminal-report/src/installLogsPrinter')(on, loggerOptions);
    
          on('task', {
            getDownload: () => {
              const downloadsFolder = config['downloadsFolder'];
    
              if (!fs.existsSync(downloadsFolder)) {
                fs.mkdirSync(downloadsFolder);
              }
    
              return new Promise((resolve, reject) => {
                const watcher = fs.watch(downloadsFolder, (eventType, filename) => {
                  if (eventType === 'rename' && !filename.endsWith('.crdownload') && !filename.endsWith('.part')) {
                    resolve(filename);
                    watcher.close();
                  }
                });
    
                setTimeout(reject, config.taskTimeout);
              });
            }
          });
    
          const file = config.env.configFile || 'dev';
    
          return getConfigurationByFile(file);
        },
      },
    });

    I do not see anything outstanding here that could cause issues with cy.writeFile() inside some custom class though.

  17. rashmiranjanbhoi commented on Jul 3, 2023

    @rashmiranjanbhoi

    I have the same issue - only showing up in headless mode in Cypress version 12.16.0

    image

    Note :- This is inconsistent; occasionally it succeeds, occasionally it fails.

  18. bimanpathirage commented on Jul 5, 2023

    @bimanpathirage

    We're aware of the "must only be invoked from the spec file or support file" issue and are looking into it now. Until a fix is identified, tested, and released you can temporarily downgrade to Cypress v12.14.0 which does not exhibit this issue.

    Can I please know the way to downgrade the version? TIA

  19. MikeMcC399 commented on Jul 5, 2023

    @MikeMcC399
    Contributor

    @bimanpathirage

    Can I please know the way to downgrade the version? TIA

    If you are using npm, then simply

    npm install cypress@12.14.0 --save-dev --exact

    For Yarn

    yarn add cypress@12.14.0 --dev --exact
  20. bahmutov commented on Jul 6, 2023

    @bahmutov
    Contributor

    Reproducible example (still fails with 12.17.0) in bahmutov/cypress-examples#174
    Can be seen in branch 12.16

    npx cypress run --spec ./docs/commands/files.md,./docs/recipes/collect-headings.md
    
      Running:  commands/files.md                                                               (1 of 2)
    
    
      Files
        ✓ cy.fixture() - load a fixture (767ms)
        - cy.fixture() or require - load a fixture
        ✓ cy.readFile() - read file contents (75ms)
        1) cy.writeFile() - write to a file
        2) cy.writeFile() - write combined JSON object
        3) cy.writeFile() - write combined JSON array
    
    
      2 passing (3s)
      1 pending
      3 failing
    
      1) Files
           cy.writeFile() - write to a file:
         CypressError: `cy.writeFile()` must only be invoked from the spec file or support file.
          at <unknown> (http://localhost:65471/__cypress/runner/cypress_runner.js:146497:87)
          at tryCatcher (http://localhost:65471/__cypress/runner/cypress_runner.js:18744:23)
          at Promise._settlePromiseFromHandler (http://localhost:65471/__cypress/runner/cypress_runner.js:16679:31)
          at Promise._settlePromise (http://localhost:65471/__cypress/runner/cypress_runner.js:16736:18)
          at Promise._settlePromise0 (http://localhost:65471/__cypress/runner/cypress_runner.js:16781:10)
          at Promise._settlePromises (http://localhost:65471/__cypress/runner/cypress_runner.js:16857:18)
          at _drainQueueStep (http://localhost:65471/__cypress/runner/cypress_runner.js:13451:12)
          at _drainQueue (http://localhost:65471/__cypress/runner/cypress_runner.js:13444:9)
          at ../../node_modules/bluebird/js/release/async.js.Async._drainQueues (http://localhost:65471/__cypress/runner/cypress_runner.js:13460:5)
          at Async.drainQueues (http://localhost:65471/__cypress/runner/cypress_runner.js:13330:14)
      From Your Spec Code:
          at Context.eval (http://localhost:65471/__cypress/tests?p=docs/commands/files.md)
    
  21. chrisbreiding commented on Jul 7, 2023

    @chrisbreiding
    Contributor

    Thanks for the repro, @bahmutov! That's a new edge case and being able to reproduce it will help a lot in debugging it.

  22. cypress-bot commented on Jul 20, 2023

    @cypress-bot
    Contributor

    Released in 12.17.2.

    This comment thread has been locked. If you are still experiencing this issue after upgrading to
    Cypress v12.17.2, please open a new issue.

  23. locked as resolved and limited conversation to collaborators on Jul 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions