Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cy.writeFiles runs into errors #27097

Closed
JanUrb opened this issue Jun 21, 2023 · 21 comments · Fixed by #27267
Closed

cy.writeFiles runs into errors #27097

JanUrb opened this issue Jun 21, 2023 · 21 comments · Fixed by #27267
Assignees

Comments

@JanUrb
Copy link

JanUrb commented Jun 21, 2023

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

@dubzzz
Copy link

dubzzz commented Jun 21, 2023

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

@ddnexus
Copy link

ddnexus commented Jun 21, 2023

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.

@JanUrb JanUrb changed the title cy.writeFiles cy.writeFiles runs into errors Jun 21, 2023
@gabor-szallas
Copy link

gabor-szallas commented Jun 21, 2023

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.

@mike-plummer
Copy link
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.

@mike-plummer
Copy link
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

@mike-plummer mike-plummer closed this as not planned Won't fix, can't repro, duplicate, stale Jun 21, 2023
@arundavid1987
Copy link

image

@mike-plummer
Copy link
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!

@bdimitrovski
Copy link

bdimitrovski commented Jun 27, 2023

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?

@mike-plummer
Copy link
Contributor

mike-plummer commented Jun 27, 2023

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?

@bdimitrovski
Copy link

bdimitrovski commented Jun 27, 2023

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?

@chrisbreiding chrisbreiding self-assigned this Jun 27, 2023
@elGatoMantocko
Copy link

elGatoMantocko commented Jun 27, 2023

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

#27099 (comment)

@chrisbreiding
Copy link
Contributor

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

@chrisbreiding
Copy link
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()

@Jacek-fstack
Copy link

Jacek-fstack commented Jun 30, 2023

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

@bdimitrovski
Copy link

bdimitrovski commented Jun 30, 2023

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.

@rashmiranjanbhoi
Copy link

rashmiranjanbhoi commented Jul 3, 2023

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.

@bimanpathirage
Copy link

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

@MikeMcC399
Copy link
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

@bahmutov
Copy link
Contributor

bahmutov commented Jul 6, 2023

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)

@chrisbreiding
Copy link
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.

@cypress-bot
Copy link
Contributor

cypress-bot bot commented Jul 20, 2023

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.

@cypress-bot cypress-bot bot locked as resolved and limited conversation to collaborators Jul 20, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.