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 | const cypress = require('cypress') |
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 | $ npm i -D cypress-json-results |
1 | module.exports = (on, config) => { |
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.
1 | { |
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.