cypress-multithreaded-runner
v2.2.0
Published
A lightweight method to run Cypress spec files in multiple threads, with built-in support for Allure report generation
Readme
cypress-multithreaded-runner
A lightweight method to run Cypress spec files in multiple threads, with built-in support for Allure report generation.
When used out of the box, Cypress will only run your spec files in a single thread. It also won't create any kind of easy-to-read report once the tests have completed. By making use of this module, you'll be able to adapt your Cypress project to run much faster than before, while also generating a comprehensive Allure report for every run.
NOTE: Currently, generating core Allure files are needed in order for this module to function correctly, but this may change later.
Prerequisites
- Node 22 or above
- Java (only needed to generate the full Allure report)
- A Cypress project (version 15 or above; tested on
16.4) - @cypress/grep (optional: only needed if you want to use Cypress grep features)
Setup
In its current form, you can import the runner into a simple node application, initialising it like so:
const runner = require("cypress-multithreaded-runner");
const cypressConfigOverride = {
reportDir: "put-the-reports-here",
};
runner({
phaseDefaults: {
cypressConfig: {
filepath: "src/cypress/configurations/my-generic-cypress.config.js",
object: cypressConfigOverride,
},
grep: "my-test",
grepTags: "my-tag",
},
phases: [
{
specsDir: "src/cypress/tests/phase1",
},
{
specsDir: "src/cypress/tests/phase2",
},
],
allureReportDir: "i-would-rather-save-the-allure-report-here",
reportDir: cypressConfigOverride.reportDir,
waitForFileExist: {
filepath: "a-file-that-I-expect-to-exist-before-subsequent-threads-run.txt",
timeout: 60,
deleteAfterCompletion: true,
},
});By default, every spec file within each phase's specsDir will spawn a unique instance of Cypress. Once everything's been tested, the Allure report will be generated.
A benchmark file will also be generated. This will dictate the optimal order in which the threads should spawn in future. Some identifiers from your config are used to determine which order should be used. That way, you can run your Cypress tests with different arguments (for example, different grep arguments) and the results will not interfere with other benchmarks.
Should tests in any phase fail, all threads from subsequent phases will stop immediately. If you don't want this to happen, you'll want to just use one phase (or set stopSubsequentPhasesOnFail to false).
If you only need one phase, the phase options (such as specsDir, cypressConfig and grep) can be given at the top level of the config instead of using phases.
How tests are counted
Before any Cypress instance starts, every spec file is evaluated in Node (with a stand-in for Cypress & Mocha) to find every test it contains. Tests created dynamically are counted too, for example tests created in loops, with it.each/describe.each (in the style of cypress-each), with Cypress._.times, from imported fixtures, from Cypress.expose()/Cypress.env() values or by helper functions defined in your support file. Those values are worked out as Cypress would: from your config file, cypress.env.json, CYPRESS_ environment variables and the phase's env args, and then by running your config file's setupNodeEvents (once for each different phase config, in a separate process, with a 30 second time limit) so that values it sets are known too. Your config file is loaded with Node, as Cypress loads it (TypeScript included), so files it uses can rely on __dirname, e.g. to find a .env file. Events it registers with on aren't run. If it fails, tests are discovered without the values it would have set, and the reason is shown when verbose is enabled. .only, .skip and your grep/grepTags/grepUntagged options are taken into account. Should a spec file not be possible to evaluate, a warning is shown and its tests are found with a text search instead.
This is used to make the Allure report trustworthy:
- If a thread crashes (and runs out of restarts) or times out, every test that didn't produce a result is added to the Allure report as broken. If a thread is stopped (or never starts) because a thread in an earlier phase failed, its tests are added as failed. If Cypress finishes running a thread's spec file but some of its tests don't produce a result (or none of them do, which usually means that the Allure writer isn't set up properly), those tests are added as unknown, and the thread is reported as an error. The exception is a thread that produced a result for a test that wasn't found in the spec file, most likely because the test's title is only known at runtime: its tests without a result are probably the same tests under different titles, so they aren't added. Tests that are intentionally skipped (e.g.
it.skip) are always added as skipped. A warning at the top of the report explains which threads didn't complete. Either way, the number of tests in the report is complete. - If only previously failed spec files are run (
runFailedSpecFilesFromReportURL,runFailedSpecFilesFromObjectorrunMostRecentlyFailedSpecFilesFromReportsDir), every other spec file is assumed to have passed previously. Their tests are added to the Allure report as passed (so they count towards thesuccessPercentage), with a message explaining why. Tests in them that are intentionally skipped are added as skipped. - The benchmark's
successPercentageis worked out as on the Allure report's overview, so the two always match: it's the percentage of tests that passed, out of the tests that passed, failed or were broken, rounded down to 2 decimal places. Tests that were skipped (e.g. withit.skip) and tests whose result is unknown aren't counted. Tests in spec files that weren't run because they passed previously count as passed. Tests that were meant to run but didn't (e.g. because their phase was stopped) are failed tests, so they count against the percentage. The thread performance summary gives the same percentage, saying which tests it leaves out. A breakdown is saved in the benchmark undertests.
Generating the Allure report
To generate Allure reports, you will need to add the following import to your support file:
import "cypress-multithreaded-runner/allure";In addition, add the following import to your config file:
const allureWriter = require("cypress-multithreaded-runner/allure/writer");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
allureWriter(on, config);
return config;
},
},
});If this code is missing, the threads won't produce any results, so every test will be added to the Allure report with an unknown result (see How tests are counted).
You can import a different Allure generator if you wish, such as @mmisty/cypress-allure-adapter. Other Allure generators may not work correctly without modification.
Optional: Grep
If you want to make use of @cypress/grep, add it as a dependency to your project and follow the official readme to see how to import it. Refer to the options table to see what features are supported by cypress-multithreaded-runner out of the box.
Using grep in conjunction with onlyRunSpecFilesIncludingAnyText / onlyRunSpecFilesIncludingAllText / onlyRunSpecFilesNotIncludingAnyText / onlyRunSpecFilesNotIncludingAllText
Grep can be a little slow if you have a lot of spec files, as Cypress will still try to run each of them before evaluating whether they satisfy the grep rules.
To save time, you may want to utilise onlyRunSpecFilesIncludingAnyText and/or onlyRunSpecFilesIncludingAllText, onlyRunSpecFilesNotIncludingAnyText & onlyRunSpecFilesNotIncludingAllText in addition to grep. These properties will ensure that spec files will only be processed if the given string(s) are/are not found within them. Unlike grep, the filtering will occur before Cypress is launched, which in practice will mean you can expect a significant speed boost in many scenarios. However, as it's only checking for the presence of strings, you shouldn't pass through advanced grep rules to these properties.
While it may be a common use case, you don't need to use grep in order for these properties to function. The values you assign to these properties do not need to be the same as the ones you give to grep or grepTags, as it works completely independently.
For basic grep rules, the following example may represent a common use case:
const runner = require("cypress-multithreaded-runner");
const cypressConfigOverride = {
reportDir: "put-the-reports-here",
};
runner({
cypressConfig: {
filepath: "src/cypress/configurations/my-generic-cypress.config.js",
object: cypressConfigOverride,
},
reportDir: cypressConfigOverride.reportDir,
specsDir: "src/cypress/tests",
grep: "my-test",
grepTags: "my-tag",
onlyRunSpecFilesIncludingAllText: ["my-test", "my-tag"],
ignoreCliOverrides: ["grep", "grepTags"],
});Optional: Prevent the parent process from ending when tests fail
By default, this module will end the parent process (with exit code 1) should the tests complete with one or more failures. Bypassing this will therefore allow your app to continue running every time the tests complete. You can set endProcessIfTestsFail to false to achieve this.
Optional: Dry run
Set dryRun to true (or pass --dry-run in the command line) to simulate a run with your config without running any spec files, for example to check which spec files would run in which threads and phases, how many tests they contain, and what the reports look like. Instead of starting Cypress, each thread gives every test in its spec file (see How tests are counted) a placeholder result that passes. Tests that are skipped anyway (e.g. with it.skip) are skipped, but a test that skips itself while it runs can't be known about, so it passes. The reports are then generated as usual, each saying that it was a dry run.
Nothing outside the reportDir is updated: the thread benchmark and the Allure history aren't saved, the JUnit report isn't uploaded to BrowserStack Test Observability, and waitForFileExist is ignored, as no test will create the file.
Optional: Generate JUnit reports & upload to BrowserStack Test Observability
An additional JUnit report can be generated alongside Allure. It's built from the same results as the Allure report, so the two always agree: it has every test once, with its final result, including tests that were filled in because their thread crashed, timed out, was stopped or didn't produce any results, and tests in spec files that weren't re-run (see How tests are counted). Earlier results of a retried test are left out, as the Allure report shows them as retries. This report can also be uploaded to BrowserStack Test Observability, if you have an account with them. A report without any tests isn't uploaded:
const runner = require("cypress-multithreaded-runner");
const cypressConfigOverride = {
reportDir: "put-the-reports-here",
};
runner({
cypressConfig: {
filepath: "src/cypress/configurations/my-generic-cypress.config.js",
object: cypressConfigOverride,
},
reportDir: cypressConfigOverride.reportDir,
specsDir: "src/cypress/tests",
jUnitReport: {
enabled: true,
browserStackTestObservabilityUpload: {
username: "my-browserstack-username",
accessKey: "my-browserstack-key",
parameters: {
projectName: "my-project-name",
buildName: "my-build-name",
},
},
},
});Get the exit code
Unless an error unrelated to one of your tests occurs, you can get the aforementioned exit code by running this module in async mode. To achieve this, import and use the module like so:
const asyncRunner = require("cypress-multithreaded-runner/async"); // different import
const cypressConfigOverride = {
reportDir: "put-the-reports-here",
};
(async () => {
const exitCode = await asyncRunner({
cypressConfig: {
filepath: "src/cypress/configurations/my-generic-cypress.config.js",
object: cypressConfigOverride,
},
reportDir: cypressConfigOverride.reportDir,
specsDir: "src/cypress/tests",
endProcessIfTestsFail: false, // if this isn't set to false, your app will stop running if any tests fail!
});
console.log("exitCode: ", exitCode);
})();The exit code will be 0 if all tests pass and 1 if any test fails.
General guidance
Pay attention to the performance of each thread when adding a new test. It is a good idea to try making the accumulation of tests in each thread take roughly the same amount of time to finish running, as any thread that takes significantly longer than the others will be a bottleneck! Therefore, try to add any new tests to threads which aren't oversaturated. You can have a look at how each thread is performing by viewing the "Thread Performance Summary" & other logs, all of which will be added to the bottom of the Allure report as well as in separate text files.
Diminishing returns will be observable the more threads you add, as most computers have a relatively low number of threads that can be actively used at any given time. When too many threads are added you may notice a large increase in the frequency of failing tests, and you may also actually notice that other threads are just running slower in general. It's all a bit of a balancing act if you want to get it all just right.
None of the Cypress threads can "talk" to each other, so your project may need a bit of extra configuration if this is needed. For example, let's say your first thread logs in to a website and you'd like this session to be maintained across your other threads. You could have the first Cypress thread log in and then save a file containing all of the cookies that the other threads need. You can make use of the waitForFileExist option to help make such functionality possible for your project. cypress-wordpress-session is an example of a Cypress addon that can be used to create & load a cookies file for a persistent session across multiple threads.
Overriding options in the command line
The module makes use of argv to allow options to be overridden via the command line. Arguments passed in via the command line will take precedence over any options set via your node application. For example, let's say you want to override the reportDir option. You can run your node application with a standard kebab-case argument (eg. --report-dir="my-report-dir") and the reportDir will be overridden.
Options
| Name | Type | Default value | Description |
| ---------------------------------------------- | ---------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| reportDir | string | null | The location to save the full report to: the Allure results & report, every thread's logs and the thread performance summary. If it isn't set, the current working directory is used. |
| clean | boolean | false | Delete all files in the reportDir before starting the threads. |
| verbose | boolean | false | Print extra detail about what the runner is doing, such as which Cypress version it found, why a spec file's tests couldn't be discovered, when each thread's run starts and why a thread was restarted. Useful when something isn't behaving as expected. |
| dryRun | boolean | false | Simulate a run without running any spec files. Every test is given a placeholder result that passes (or is skipped, if the test is skipped anyway, e.g. with it.skip), and the reports are generated as usual. Nothing outside the reportDir is updated. See Optional: Dry run. |
| allureReportDir | string | <reportDir>/allure-report | The location to save just the Allure report. |
| allureHistoryDir | string | <reportDir>/allure-results/history | The location to retrieve & overwrite just the Allure history. |
| overwriteAllureHistory | boolean | true | Copy the Allure history to the allureHistoryDir after the tests have run. Useful only if the allureHistoryDir is different to default location. |
| allureReportHeading | string | null | A custom heading to add to the top of the Allure report. |
| includeRepoPath | boolean / string | true | Link each spec file named in the runner's sections of the Allure report (the summary at the top, and each thread's heading and the Thread Performance Summary at the bottom) to that file in its git repo, at the commit that was tested.true: if the spec files are in a git repo, link to them on the site hosting it, at the commit that's checked out (HEAD). The site's address comes from the repo's origin remote (or its first remote, if there's no origin). GitHub, GitLab, Bitbucket and Azure DevOps are recognised, and any other host is assumed to lay out its files like GitHub (as GitHub Enterprise and Gitea do). There are no links if the spec files aren't in a git repo, if it has no remote, or if the remote is a local path or an ssh alias. Credentials in the remote's URL are never included.A URL: link to the spec files there instead, e.g. https://github.com/acme/widgets/blob/main. Each spec file's path within the repo is added to the end (or its path within the current directory, if it isn't in a git repo).Anything falsy (e.g. false): don't link to the spec files.Bear in mind that a link only works once its commit has been pushed, and shows the spec file as it was committed (without any changes that hadn't been). Via the CLI: --include-repo-path <url>, or --no-include-repo-path. |
| generateAllure | boolean | true | Generate the Allure report. Overrides the openAllure, combineAllure & hostAllure options if set to false. When false, Java isn't required, and a summary of the run (including the list of failed spec files) is saved to <reportDir>/cmr-summary.json. |
| generate | boolean | true | CLI alias for generateAllure. |
| openAllure | boolean | false | Open the Allure report after it's generated.If combineAllure is also passed in, it'll open the combined Allure report instead.If hostAllure is also passed in, openAllure will be ignored. |
| open | boolean | false | CLI alias for openAllure. |
| combineAllure | boolean | true | Combine the Allure report into a single file (complete.html). |
| combine | boolean | true | CLI alias for combineAllure. |
| hostAllure | boolean | false | Spin up a localhost for the Allure report after it's generated. |
| host | boolean | false | CLI alias for hostAllure. |
| ignoreCliOverrides | arrayOf(string) | null | A list of keys of properties that you don't want the CLI to override when you run an instance of cypress-multithreaded-runner. This will enable your node app to do a custom override that uses a combination of the CLI and itself. See here for an example. |
| specFiles | arrayOf(string) | null | An array of one or more spec files to filter. Only spec files present in the array will be tested. This will apply to every phase, so you may find some phases are skipped entirely. The files must all exist within the given specsDir directory. |
| specs | arrayOf(string) | null | CLI alias for specFiles. |
| runFailedSpecFilesFromReportURL | string | null | Provide a URL/filepath (remote or local) of an Allure report generated by Cypress Multithreaded Runner (v1.15 and above), or of its cmr-summary.json file, to only run the spec files that failed in that particular run. Every other spec file is assumed to have passed (see How tests are counted). Check lib/config/cliArgs.js to see the aliases. |
| runFailedSpecFilesFromObject | array / object | null | Provide either an array of spec file paths, or a JSON object (or JSON string, e.g. via the CLI) in which the first array with the key fails will be found by searching recursively (e.g. a benchmark JSON file's contents, including one nested inside another object). Those spec files will be the only ones run, and every other spec file is assumed to have passed (see How tests are counted). |
| runMostRecentlyFailedSpecFilesFromReportsDir | string | null | Recursively search for Allure reports (and cmr-summary.json files) within a directory, in order of newest to oldest, and run the spec files from the most recent one containing failed tests. Every other spec file is assumed to have passed (see How tests are counted). Check lib/config/cliArgs.js to see the aliases. |
| logMode | oneOf([1,2,3,4]) | 1 | The method by which you want each Cypress thread to print logs to the console.1: Only print logs from one thread at a time, in order of when each thread began. Only when the first thread completes will the logs from the second thread be printed, then the third and so on.2: Only print logs from one thread at a time, but allow non-chronology. Should any other thread complete before the current one does, these logs will be "queued" and then print when the current one completes. For example, let's say thread 3 completes before thread 1 completes, with thread 2 completing at the end. In this scenario, you can expect to see all of the output for thread 1, then all of thread 3, then thread 2.3: Print any log from any thread as soon as it manifests. This will likely mean that you see a mix of logs from each thread, and can be difficult to understand the continuity in the logs the more threads you have.4: Identical to mode 3, except that when all threads complete, print all logs again but separate out all of the threads. |
| waitForFileExist | object | null | Wait for a specific file to exist (and larger than 0 bytes in size) before subsequent threads begin. For specific options, see the table below. |
| maxThreadRestarts | number | 5 | Should an instance of Cypress crash, it may be restarted up to this many times until all threads complete successfully. Note that, by default, any spec file that fails in a before or beforeEach hook will be considered a crash. What counts as a crash can be changed with crashPatterns. |
| crashPatterns | arrayOf(string) | See description | The text that marks a Cypress crash. If the output Cypress prints in a thread (or the Allure results it writes) contains any of these, the thread is considered to have crashed, and is restarted (see maxThreadRestarts) rather than failed. Matching is case-insensitive. Setting this option replaces the defaults rather than adding to them, so copy any of the defaults you still want. An empty array means that no text is ever treated as a crash (a Cypress run that never finishes, or stops responding, still is). Via the CLI: --crash-patterns "first pattern" "second pattern".The defaults are listed in lib/cypress/crashPatterns.js. |
| maxConcurrentThreads | number | Half the number of available threads | The maximum number of threads that'll run at any one time. By default, this will be the number of threads the client's CPU is reporting divided by two. It's recommended not to use more threads than a CPU can provide, otherwise performance is likely to be negatively affected. If not enough threads are available, cypress-multithreaded-runner will wait for any of the currently running Cypress instances to complete before starting another one. This process will repeat until all tests are completed. |
| notify | boolean | true | Fire a platform native notification when tests have completed |
| threadDelay | number | 30 | The number of seconds to wait before starting the next thread, unless the current Cypress instance has already started running. If waitForFileExist has been set, the 2nd thread will continue waiting until the given file exists. For more info, see the table below. |
| onlyPhaseNo | number | null | Set this to the value of any of the phases to run just the threads within that phase. Phases count from a value of 1, not 0. |
| startingPhaseNo | number | null | Set this to the value of any of the phases to run just the threads within and after that phase. Phases count from a value of 1, not 0. |
| endingPhaseNo | number | null | Set this to the value of any of the phases to run just the threads before and within that phase. Phases count from a value of 1, not 0.
