DEV Community

Srikanth Kyatham
Srikanth Kyatham

Posted on • Edited on

2 1

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay