• Stars
    star
    411
  • Rank 101,435 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 5 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Saves the code coverage collected during Cypress tests

@cypress/code-coverage renovate-app badge CircleCI

Saves the code coverage collected during Cypress tests

Install

npm install -D @cypress/code-coverage

Note: this plugin assumes cypress is a peer dependency already installed in your project.

Add to your cypress/support/index.js file

import '@cypress/code-coverage/support'

Register tasks in your cypress/plugins/index.js file

module.exports = (on, config) => {
  require('@cypress/code-coverage/task')(on, config)

  // add other tasks to be registered here

  // IMPORTANT to return the config object
  // with the any changed environment variables
  return config
}

Instrument your application

This plugin DOES NOT instrument your code. You have to instrument it yourself using Istanbul.js tool. Luckily it is not difficult. For example, if you are already using Babel to transpile you can add babel-plugin-istanbul to your .babelrc and instrument on the fly.

{
  "plugins": ["istanbul"]
}

Please see the Test Apps section down below, you can probably find a linked project matching your situation to see how to instrument your application's source code before running end-to-end tests to get the code coverage.

If your application has been instrumented correctly, then you should see additional counters and instructions in the application's JavaScript resources, like the image down below shows.

Instrumented code

You should see the window.__coverage__ object in the "Application under test iframe"

Window coverage object

If you have instrumented your application's code and see the window.__coverage__ object, then this plugin will save the coverage into .nyc_output folder and will generate reports after the tests finish (even in the interactive mode). Find the LCOV and HTML report in the coverage/lcov-report folder.

Coverage report

That should be it! You should see messages from this plugin in the Cypress Command Log

Plugin messages

More information

App vs unit tests

You need to instrument your web application. This means that when the test does cy.visit('localhost:3000') any code the index.html requests should be instrumented by YOU. See Test Apps section for advice, usually you need to stick babel-plugin-istanbul into your pipeline somewhere.

If you are testing individual functions from your application code by importing them directly into Cypress spec files, this is called "unit tests" and Cypress can instrument this scenario for you. See Instrument unit tests section.

Reports

The coverage folder has results in several formats, and the coverage raw data is stored in .nyc_output folder. You can see the coverage numbers yourself. This plugin has nyc as a dependency, so it should be available right away. Here are common examples:

# see just the coverage summary
$ npx nyc report --reporter=text-summary
# see just the coverage file by file
$ npx nyc report --reporter=text
# save the HTML report again
$ npx nyc report --reporter=lcov

It is useful to enforce minimum coverage numbers. For example:

$ npx nyc report --check-coverage --lines 80
----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 main.js  |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------

$ npx nyc report --check-coverage --lines 101
----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 main.js  |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------
ERROR: Coverage for lines (100%) does not meet global threshold (101%)

Watch video How to read code coverage report to see how to read the HTML coverage report.

Instrument unit tests

If you test your application code directly from specs you might want to instrument them and combine unit test code coverage with any end-to-end code coverage (from iframe). You can easily instrument spec files using babel-plugin-istanbul for example.

Install the plugin

npm i -D babel-plugin-istanbul

Set your .babelrc file

{
  "plugins": ["istanbul"]
}

Put the following in cypress/plugins/index.js file to use .babelrc file

module.exports = (on, config) => {
  require('@cypress/code-coverage/task')(on, config)
  on('file:preprocessor', require('@cypress/code-coverage/use-babelrc'))
  return config
}

Now the code coverage from spec files will be combined with end-to-end coverage.

Find example of a just the unit tests and JavaScript source files with collected code coverage in test-apps/new-cypress-config/unit-tests-js.

Alternative for unit tests

If you cannot use .babelrc for some reason (maybe it is used by other tools?), try using the Browserify transformer included with this module in use-browserify-istanbul file.

module.exports = (on, config) => {
  require('@cypress/code-coverage/task')(on, config)
  on(
    'file:preprocessor',
    require('@cypress/code-coverage/use-browserify-istanbul')
  )
  return config
}

Instrument backend code

Example in test-apps/new-cypress-config/backend folder.

You can also instrument your server-side code and produce combined coverage report that covers both the backend and frontend code

  1. Run the server code with instrumentation. The simplest way is to use nyc. If normally you run node src/server then to run instrumented version you can do nyc --silent node src/server.
  2. Add an endpoint that returns collected coverage. If you are using Express, you can simply do
const express = require('express')
const app = express()
require('@cypress/code-coverage/middleware/express')(app)

Tip: you can register the endpoint only if there is global code coverage object, and you can exclude the middleware code from the coverage numbers

// https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md
/* istanbul ignore next */
if (global.__coverage__) {
  require('@cypress/code-coverage/middleware/express')(app)
}

If you use Hapi server, define the endpoint yourself and return the object

if (global.__coverage__) {
  require('@cypress/code-coverage/middleware/hapi')(server)
}

For any other server, define the endpoint yourself and return the coverage object:

if (global.__coverage__) {
  // add method "GET /__coverage__" and response with JSON
  onRequest = (response) => response.sendJSON({ coverage: global.__coverage__ })
}
  1. Save the API coverage endpoint in cypress.json file to let the plugin know where to call to receive the code coverage data from the server. Place it in env.codeCoverage object:
{
  "env": {
    "codeCoverage": {
      "url": "http://localhost:3000/__coverage__"
    }
  }
}

That should be enough - the code coverage from the server will be requested at the end of the test run and merged with the client-side code coverage, producing a combined report.

expectBackendCoverageOnly

If there is NO frontend code coverage, and you want to only collect the backend code coverage using Cypress tests, set expectBackendCoverageOnly: true in cypress.json file. Otherwise Cypress complains that it cannot find the frontend code coverage.

Default:

No frontend code coverage warning

After:

{
  "env": {
    "codeCoverage": {
      "url": "http://localhost:3003/__coverage__",
      "expectBackendCoverageOnly": true
    }
  }
}

Cypress knows to expect the backend code coverage only

Custom report folder

You can specify custom report folder by adding nyc object to the package.json file. For example to save reports to cypress-coverage folder, use:

{
  "nyc": {
    "report-dir": "cypress-coverage"
  }
}

Custom reporters

You can specify custom coverage reporter(s) to use. For example to output text summary and save JSON report in cypress-coverage folder set in your package.json folder:

{
  "nyc": {
    "report-dir": "cypress-coverage",
    "reporter": ["text", "json"]
  }
}

Tip: find list of reporters here

Custom NYC command

Sometimes NYC tool might be installed in a different folder not in the current or parent folder, or you might want to customize the report command. In that case, put the custom command into package.json in the current folder and this plugin will automatically use it.

{
  "scripts": {
    "coverage:report": "call NYC report ..."
  }
}

TypeScript users

TypeScript source files should be automatically included in the report, if they are instrumented.

See test-apps/new-cypress-config/ts-example, bahmutov/cra-ts-code-coverage-example or bahmutov/cypress-angular-coverage-example.

Include code

By default, the code coverage report includes only the instrumented files loaded by the application during the tests. If some modules are loaded dynamically, or are loaded by the pages NOT visited during any tests, these files are not going to be in the report - because the plugin does not know about them. You can include all expected source files in the report by using include list in the package.json file. The files without counters will have 0 percent code coverage.

For example, if you want to make sure the final report includes all JS files from the "src/pages" folder, set the "nyc" object in your package.json file.

{
  "nyc": {
    "all": true,
    "include": "src/pages/*.js"
  }
}

See example test-app/all-files

Exclude code

You can exclude parts of the code or entire files from the code coverage report. See Istanbul guide. Common cases:

Exclude "else" branch

When running code only during Cypress tests, the "else" branch will never be hit. Thus we should exclude it from the branch coverage computation:

// expose "store" reference during tests
/* istanbul ignore else */
if (window.Cypress) {
  window.store = store
}

Exclude next logical statement

Often needed to skip a statement

/* istanbul ignore next */
if (global.__coverage__) {
  require('@cypress/code-coverage/middleware/express')(app)
}

Or a particular switch case

switch (foo) {
  case 1 /* some code */:
    break
  /* istanbul ignore next */
  case 2: // really difficult to hit from tests
    someCode()
}

Exclude files and folders

The code coverage plugin will automatically exclude any test/spec files you have defined in testFiles (Cypress < v10) or specPattern (Cypress >= v10) configuration options. Additionaly, you can set the exclude pattern glob in the code coverage environment variable to specify additional files to be excluded:

// cypress.config.js or cypress.json
env: {
  codeCoverage: {
    exclude: ['cypress/**/*.*'],
  },
},

Cypress 10 and later users should set the exclude option to exclude any items from the cypress folder they don't want to be included in the coverage reports.

Additionaly, you can use nyc configuration and include and exclude options. You can include and exclude files using minimatch patterns in .nycrc file or using "nyc" object inside your package.json file.

For example, if you want to only include files in the app folder, but exclude app/util.js file, you can set in your package.json

{
  "nyc": {
    "include": ["app/**/*.js"],
    "exclude": ["app/util.js"]
  }
}

Note: if you have all: true NYC option set, this plugin will check the produced .nyc_output/out.json before generating the final report. If the out.json file does not have information for some files that should be there according to include list, then an empty placeholder will be included, see PR 208.

Another important option is excludeAfterRemap. By default it is false, which might let excluded files through. If you are excluding the files, and the instrumenter does not respect the nyc.exclude setting, then add excludeAfterRemap: true to tell nyc report to exclude files. See test-apps/exclude-files.

Disable plugin

You can skip the client-side code coverage hooks by setting the environment variable coverage to false.

# tell Cypress to set environment variable "coverage" to false
cypress run --env coverage=false
# or pass the environment variable
CYPRESS_COVERAGE=false cypress run

or set it to false in the cypress.json file

{
  "env": {
    "coverage": false
  }
}

See Cypress environment variables and support.js. You can try running without code coverage in this project yourself

# run with code coverage
npm run dev
# disable code coverage
npm run dev:no:coverage

Links

Examples

Internal test apps

Full examples we use for testing in this repository:

External examples

Look up the list of examples under GitHub topic cypress-code-coverage-example

Migrations

v2 to v3

Change the plugins file cypress/plugins/index.js

// BEFORE
module.exports = (on, config) => {
  on('task', require('@cypress/code-coverage/task'))
}
// AFTER
module.exports = (on, config) => {
  require('@cypress/code-coverage/task')(on, config)
  // IMPORTANT to return the config object
  // with the any changed environment variables
  return config
}

Tip: we include plugins.js file you can point at from your code in simple cases. From your cypress.json file:

{
  "pluginsFile": "node_modules/@cypress/code-coverage/plugins",
  "supportFile": "node_modules/@cypress/code-coverage/support"
}

See test-apps/use-plugins-and-support

Debugging

This plugin uses debug module to output additional logging messages from its task.js file. This can help with debugging errors while saving code coverage or reporting. In order to see these messages, run Cypress from the terminal with environment variable DEBUG=code-coverage. Example using Unix syntax to set the variable:

$ DEBUG=code-coverage npm run dev
...
  code-coverage reset code coverage in interactive mode +0ms
  code-coverage wrote coverage file /code-coverage/.nyc_output/out.json +28ms
  code-coverage saving coverage report using command: "nyc report --report-dir ./coverage --reporter=lcov --reporter=clover --reporter=json" +3ms

Deeply nested object will sometimes have [object Object] values printed. You can print these nested objects by specifying a deeper depth by adding DEBUG_DEPTH= setting

$ DEBUG_DEPTH=10 DEBUG=code-coverage npm run dev

Common issues

Common issue: not instrumenting your application when running Cypress.

If the plugin worked before in version X, but stopped after upgrading to version Y, please try the released versions between X and Y to see where the breaking change was.

If you decide to open an issue in this repository, please fill all information the issue template asks. The issues most likely to be resolved have debug logs, screenshots and hopefully public repository links so we can try running the tests ourselves.

Contributing

You can test changes locally by running tests and confirming the code coverage has been calculated and saved.

npm run test:ci
# now check generated coverage numbers
npx nyc report --check-coverage true --lines 80
npx nyc report --check-coverage true --lines 100 --include cypress/about.js
npx nyc report --check-coverage true --lines 100 --include cypress/unit.js

Tip: use check-code-coverage for stricter code coverage checks than nyc report --check-coverage allows.

Markdown

You can validate links in Markdown files in this directory by executing (Linux + Mac only) script

npm run check:markdown

License

This project is licensed under the terms of the MIT license.

More Repositories

1

cypress

Fast, easy and reliable testing for anything that runs in a browser.
JavaScript
46,071
star
2

cypress-realworld-app

A payment application to demonstrate real-world usage of Cypress testing methods, patterns, and workflows.
TypeScript
5,145
star
3

cypress-example-recipes

Various recipes for testing common scenarios with Cypress
JavaScript
3,113
star
4

github-action

GitHub Action for running Cypress end-to-end & component tests
JavaScript
1,294
star
5

cypress-example-kitchensink

This is an example app used to showcase Cypress.io testing.
HTML
1,130
star
6

cypress-docker-images

Docker images with Cypress dependencies and browsers
Dockerfile
906
star
7

cypress-documentation

Cypress Documentation including Guides, API, Plugins, Examples, & FAQ.
TypeScript
827
star
8

eslint-plugin-cypress

An ESLint plugin for projects that use Cypress
JavaScript
692
star
9

cypress-react-unit-test

Unit test React components using Cypress
678
star
10

testing-workshop-cypress

End-to-end testing workshop with Cypress
JavaScript
474
star
11

cypress-vue-unit-test

A little helper to unit test Vue components in the Cypress.io E2E test runner
294
star
12

cypress-example-todomvc

The official TodoMVC tests written in Cypress.
JavaScript
237
star
13

cypress-and-jest-typescript-example

Example using Jest and Cypress with TypeScript in a single repo
TypeScript
231
star
14

cypress-chrome-recorder

Export Cypress Tests from Google Chrome DevTools' Recorder
TypeScript
223
star
15

cypress-skip-test

Simple commands to skip a test based on platform, browser or a url
JavaScript
178
star
16

circleci-orb

Install, cache and run Cypress.io tests on CircleCI with minimal configuration.
156
star
17

cypress-recorder-extension

JavaScript
147
star
18

cypress-xpath

Adds XPath command to Cypress test runner
JavaScript
146
star
19

cypress-example-docker-compose

Example running Cypress tests against Apache server via docker-compose
JavaScript
142
star
20

cypress-fiddle

Quickly generates Cypress tests from HTML and JS code
JavaScript
138
star
21

cypress-grep

Filter tests using substring
JavaScript
138
star
22

cypress-example-docker-circle

Cypress + Docker + CircleCI = ❤️
JavaScript
124
star
23

cypress-example-api-testing

[ARCHIVED] Cypress E2E runner can also test Rest and other APIs
JavaScript
120
star
24

snapshot

Adds value / object / DOM element snapshot testing support to Cypress test runner
JavaScript
115
star
25

cypress-example-conduit-app

[ARCHIVED] Conduit example blogging app.
JavaScript
108
star
26

cypress-webpack-preprocessor

Cypress preprocessor for bundling JavaScript via webpack
93
star
27

add-cypress-custom-command-in-typescript

Testing how new Cypress commands are added in TypeScript
TypeScript
88
star
28

netlify-plugin-cypress

Runs Cypress end-to-end tests after Netlify builds the site but before it is deployed
JavaScript
88
star
29

chromium-downloads

A website that helps users to find and download archived Chromium versions.
JavaScript
83
star
30

cypress-realworld-testing

Next.js project for learn.cypress.io
MDX
72
star
31

schema-tools

Validate, sanitize and document JSON schemas
TypeScript
72
star
32

cypress-realworld-testing-course-app

TypeScript
65
star
33

instrument-cra

Little module for CRA applications to instrument code without ejecting react-scripts
JavaScript
63
star
34

cypress-component-testing-apps

TypeScript
59
star
35

cypress-test-tiny

Tiny Cypress E2E test case
JavaScript
52
star
36

cypress-example-todomvc-redux

Example TodoMVC application with full code coverage
JavaScript
51
star
37

cypress-test-nested-projects

[ARCHIVED] Tests Cypress running tests in subfolders
JavaScript
48
star
38

xvfb

Easily start and stop an X Virtual Frame Buffer from your node apps
JavaScript
40
star
39

cypress-tutorial-build-todo

Step by step code for the Cypress tutorial in which we build and test a todo app
JavaScript
39
star
40

cypress-tutorial-build-todo-starter

Starter project for the Cypress tutorial in which we build and test a todo app
CSS
38
star
41

cypress-cli

CLI for Cypress.io Desktop App
CoffeeScript
38
star
42

cypress-component-testing-examples

Cypress component examples
JavaScript
33
star
43

birdboard

Example Twitter client web app shown in Cypress in a Nutshell webcast.
JavaScript
33
star
44

cypress-example-docker-circle-workflows

Cypress + Docker + CircleCI Workflows = ❤️
JavaScript
29
star
45

cypress-example-circleci-orb

Demo of using the Cypress CircleCI Orb
JavaScript
28
star
46

cypress-test-example-repos

[ARCHIVED] Tests new version of Cypress against multiple projects
JavaScript
27
star
47

cypress-workshop-ci

A workshop that teaches you how to run Cypress on major CI providers
CSS
27
star
48

angular-pizza-creator

Example Angular Pizza ordering app
TypeScript
26
star
49

cypress-realworld-testing-blog

A Next.js Blog for the Real World Testing with Cypress Curriculum
JavaScript
24
star
50

cypress-browserify-preprocessor

Cypress preprocessor for bundling JavaScript via browserify
JavaScript
23
star
51

cypress-example-docker-compose-included

Cypress example with docker-compose and cypress/included image
JavaScript
20
star
52

cypress-electron-plugin

Cypress plugin for testing Electron applications
JavaScript
18
star
53

commit-info

Collects Git commit info using git
JavaScript
17
star
54

cypress-component-examples

Cypress configured with various frameworks and dev servers
JavaScript
17
star
55

cypress-heroes

Cypress Heroes Demo App
TypeScript
17
star
56

cypress-example-reporters

[ARCHIVED] Example showing multiple test reports merged into a single Mochawesome report
JavaScript
17
star
57

cra-template-cypress

The base Cypress template for Create React App
JavaScript
17
star
58

cypress-mock-ssr

Node.js Mock SSR Middleware and Cypress Commands
JavaScript
16
star
59

react-tooltip

A tooltip component for React apps
JavaScript
16
star
60

cra-template-cypress-typescript

The base Cypress + TypeScript template for Create React App
TypeScript
15
star
61

cypress-realworld-testing-todomvc

A TodoMVC Application for the Testing Your First Application Course in the Real World Testing with Cypress Curriculum
JavaScript
12
star
62

gh-action-and-gh-integration

Example project that uses both Cypress GH Action and Cypress GH Integration
JavaScript
12
star
63

cypress-example-docker-codeship

Cypress + Docker + Codeship Pro = ❤️
Dockerfile
12
star
64

cypress-example-electron

Electron.js application tested with Cypress - WIP
JavaScript
12
star
65

todomvc

Vanilla JS TodoMVC with Cypress Tests
JavaScript
11
star
66

cypress-design

Find here all the components to build UI with the Cypress Brand
TypeScript
10
star
67

cypress-gh-action-vue-example

Testing an app scaffolded with Vue CLI using Cypress GH Action
Vue
10
star
68

cypress-watch-preprocessor

Simple preprocessor that only watches files
JavaScript
8
star
69

netlify-plugin-cypress-example

An example site built and tested on Netlify using netlify-plugin-cypress
CSS
8
star
70

cypress-workshop-ci-example

A simple example app to be used during cypress-workshop-ci session
HTML
7
star
71

cypress-example-netlify-store

🛍 A Tested E-Commerce Site with Stripe payment
Vue
7
star
72

feature-maybe

Functional feature toggles on top of any object
JavaScript
6
star
73

cypress-icons

Cypress logos, icons, favicons, tray, iconset
JavaScript
6
star
74

cypress-parcel-preprocessor

Cypress preprocessor for bundling JavaScript via Parcel
JavaScript
6
star
75

cypress-test-module-api

[ARCHIVED] Example running specs using Cypress via its module API
JavaScript
6
star
76

full-network-proxy

Demo repo for Cypress with full network stubbing support
JavaScript
5
star
77

circleci-orb-parallel-example

Using Cypress CircleCI Orb to quickly run tests in parallel
JavaScript
5
star
78

v8-snapshot

Tool to create a snapshot for Electron applications.
TypeScript
5
star
79

cypress-heroes-app

Demo app for Cypress
TypeScript
5
star
80

cypress-repeat-retry

Stress-testing Cypress test retries
JavaScript
5
star
81

bumpercar

[ARCHIVED] Easily update settings and trigger builds across projects and CI providers
CoffeeScript
4
star
82

component-testing-quickstart-apps

Apps from the Cypress Component Testing quickstart guides
HTML
4
star
83

get-windows-proxy

Node.js module that finds a user's system proxy settings depending on their platform.
JavaScript
4
star
84

error-message

User-friendly error text with additional information
JavaScript
4
star
85

cypress-load-test

JavaScript
3
star
86

generator-node-cypress

Yeoman generator for PUBLIC Node packages from Cypress.io team
JavaScript
3
star
87

cypress-migrator

Apps and libraries related to the Cypress Migrator tool
TypeScript
3
star
88

cypress-adapter-ruby

Cypress Ruby Driver
Ruby
3
star
89

testing-workshop-cph

End-to-end testing workshop with Cypress at CopenhagenJS
JavaScript
3
star
90

jsnation-example

TodoMVC example tests for JSNation conference
JavaScript
3
star
91

eslint-plugin-dev

Common ESLint rules and configuration shared by Cypress packages
JavaScript
3
star
92

cypress-chrome-recorder-extension

JavaScript
2
star
93

mksnapshot

A rewrite of electron/mksnapshot to support multiple electron versions.
TypeScript
2
star
94

cypress-ct-definition-template

Template for authoring Component Framework Definitions
TypeScript
2
star
95

debugging-proxy

A simple, pass-through HTTP proxy that works with HTTP/HTTPS. For debugging applications to make sure they still work behind a proxy.
JavaScript
2
star
96

3rd-party-error

Example showing 3rd party JavaScript error
JavaScript
2
star
97

cypress-test-ci-environments

[ARCHIVED] Confirms that missing Xvfb or dependencies can be detected by Cypress
JavaScript
2
star
98

env-or-json-file

Loads JSON object from environment string or local file
JavaScript
2
star
99

cypress-onboarding-demo

JavaScript
1
star
100

circleci-orb-example

Cypress CircleCI Orb example
JavaScript
1
star