Cypress JSON Test Results

How to save the test results as a JSON file using a reporter or a plugin.

Sometimes you want to run the Cypress tests and do something based on the number of tests passed or failed. You need the test results in a JSON format, maybe saved as a text file. There are three ways to do this:

Wrap Cypress in your CLI

You can wrap the Cypress NPM module API in your CLI script. Your script will get all test results as a JSON object and then can run other programs to process the test results further.

1
2
const cypress = require('cypress')
cypress.run({ ... }).then(results => ...)

I used this approach several times, see my blog post Wrap Cypress Using NPM Module API.

Use JSON reporter

Cypress comes with built-in reporters plus you can bring your own. If you want to output JSON results into a separate file, you could try

1
npx cypress run --reporter json --reporter-options output=result.json

There is a problem though: the JSON reporter removes the standard terminal output. If you want to write the JSON results and the typical terminal output, you would need to install something like cypress-multi-reporters and configure it ... just to save the test results as a JSON file. Which brings us to the third way of saving the test results - via a plugin.

Use cypress-json-results

I wrote the plugin cypress-json-results specifically to make saving the JSON results file super simple. Install the plugin and add it to your plugin file:

1
2
$ npm i -D cypress-json-results
+ [email protected]
cypress/plugins/index.js
1
2
3
4
5
6
7
8
9
10
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config

// https://github.com/bahmutov/cypress-json-results
require('cypress-json-results')({
on,
filename: 'results.json', // default filename
})
}

Once you run the tests, you should see a message like this after all the tests have finished

1
cypress-json-results: wrote results to results.json

The saved file has each spec that executed locally with the test status.

results.json
1
2
3
4
5
6
7
8
{
"cypress/integration/spec.js": {
"receives the right text file": "passed",
"visits the text file": "passed",
"visits the Markdown file": "passed",
"converts the Markdown file": "passed"
}
}

The standard terminal output stays unchanged.

🎁 You can find the example application with cypress-json-results plugin in the repo bahmutov/check-text-file-example.