'Looking for a way to excute a command line from cypress

I need to create a file and copy it somewhere by some code from cypress .

the first step is done by using cy.writeFile and now myfile.txt is created

Now i need to copy it somewhere like c:/lib/Sth

i used this command cy.exec('cp myfile.txt c:/lib/sth')

it shows this error message :

CypressError: cy.exec('cp myfile.txt c:/lib/sth') failed because the command exited with a non-zero code. Pass {failOnNonZeroExit: false}` to ignore exit code failures. Information about the failure: Code: 127

I add {failOnNonZeroExit: false} to my code to ignore error , it works , but my file is not copied.

is there any other solution to copy my file from cypress ??



Solution 1:[1]

A work-around you could do is set up a custom cypress task to execute a command.

Something like

// cypress/plugins/index.ts
const { exec } = require('child_process');

/**
 * @type {Cypress.PluginConfig}
 */
// eslint-disable-next-line no-unused-vars
module.exports = (on, config) => {
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config

  on('task', {
    async execute(command: string) {
      return new Promise((resolve, reject) => {
        try {
          resolve(exec(command));
        } catch (e) {
          reject(e);
        }
      });
    },
  });
};

Then execute like so

cy.task('execute', 'cp myfile.txt c:/lib/sth');

This was a potential solution I came up with when cy.exec() didn't work for me either when trying to execute a relatively complex node script.

Another thing you could try is to create a really simple script that copies the file, and try executing that script.

Best of luck!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TrieuNomad