DEV Community

Srikanth Kyatham
Srikanth Kyatham

Posted on • Edited on

How to run Cypress tests in parallel with code example

Hi

Lately we have been adding multiple cypress tests and the tests run have been taking more and more time on ci and local environments as the cypress spec files are run or executed sequentially.

Luckily we have organised our tests in different folders.
I wrote a small script which would spawn cypress run for different folders.

Here is the script

// run_test_in_parallel.js
const { exec } = require("child_process");
const util = require("util");
const execPromisified = util.promisify(exec);

const baseCommand = "npx cypress run --env coverage=false --spec ";

const specs = [
  "cypress/e2e/folder1/*.cy.*",
  "cypress/e2e/folder2/*.cy.*",
];

const runCypressSpec = async (command) => {
  try {
    const { stdout, stderr } = await execPromisified(command);
    console.log("stdout:", stdout);
    console.log("stderr:", stderr);
    return Promise.resolve();
  } catch (e) {
    console.error(e);
    return Promise.reject(e);
  }
};

const runAllTests = async () => {
  const promises = specs.map((spec) => {
    const specRunCommand = baseCommand + spec;
    return runCypressSpec(specRunCommand);
  });
  console.log("all spec runs started");
  try {
    console.time("all tests");
    // using Promise.all waiting for 
    // all successful execution of test cases 
    await Promise.all(promises);
    console.timeEnd("all tests");
    // Continuous Integration expects 0 for success case
    return 0;
  } catch (e) {
    console.error(e);
    // Continuous Integration expects non-zero for failure case
    return 255;
  }
};

runAllTests();
Enter fullscreen mode Exit fullscreen mode

I have added a package.json script to run the above command

"scripts": {
  "test:e2e_run_parallel": "node ./location/of/run_test_in_parallel.js"
}
Enter fullscreen mode Exit fullscreen mode

Hope this helps any one having the same issues.

Top comments (0)