Setting up Cypress Code Coverage
On This Page What is Code Coverage in Cypress?
- What is Code Coverage in Cypress?
- Importance of Cypress Code Coverage
- Benefits of Code Coverage in Cypress
- Setting up Code Coverage in Cypress
- How to Merge Code Coverage from Parallel Tests
- What is UI Coverage in Cypress?
- Code Coverage vs UI Coverage
- App vs Unit Tests
- Why Run Cypress Tests on BrowserStack
- Utilitarian Resources for Cypress
Setting up Cypress Code Coverage
Code coverage in Cypress help track which constituent of your application code are executed during end-to-end tryout. This ensures your tests are not exclusively passing but also effectively covering critical logic. Setting it up involves instrumenting the app codification, configure plugins, and scat trial to garner and visualize reportage data.
Overview
What is Code Coverage in Cypress?
Code reportage in Cypress is the process of measuring how much of an application ’ s source codification is accomplish while running end-to-end test. Integrating tools like @ cypress/code-coverage allows you to amass and view detailed reports to identify untested parts of your codebase and ameliorate overall exam quality.
Benefits of Code Coverage in Cypress
- Improved Test Quality
- Identify Gaps
- Better Confidence in Release
- Supports Test-Driven Development (TDD)
- Optimized Testing Efforts
- Visual Feedback
Learn how to set up Cypress code reporting, understand UI coverage, how it differs from code coverage, and more.
What is Code Coverage in Cypress?
Code reporting in Cypress is the process of quantify how much of an covering ’ s source code is fulfil while scat.
It shows which lines, functions, and branches were tested, facilitate you evaluate the effectiveness of your.
Integrating puppet like @ cypress/code-coverage allows you to garner and view elaborated reports to identify untested parts of your codebase and improve overall test quality.
Code coverage is not a standard feature of. Hence, Cypress code coverage expect some setup and configuration.
Importance of Cypress Code Coverage
Code coverage is a term apply in essay to describe how easily a source code is being executed. This reveals the sections of the root code that are executed during examination execution.
As extra tests are generated and stacked, the necessity of essay particular application components may be questioned. We can appear at metrics such as functional, statement, branches, condition, and line by employing codification reporting.
- Function coverage: It quantify how many of the defined functions have been called.
- Statement Coverage: Used to trail how many program statements get been run.
- Branch Coverage: A measure of how many ramification in a control structure have be successfully executed.
- Condition Coverage: Used to observe boolean subexpressions that are examined for true and mistaken.
- Line Coverage: Counts the turn of lines of source codification that have be tested.
By measuring these different types of coverage, Cypress code coverage ensures thorough try and highlights exactly where your tests demand improvement. This makes it a critical tool for keep high-quality, dependable applications.
Follow-Up Read:
Benefits of Code Coverage in Cypress
Here are the benefits of code reporting in Cypress:
- Improved Test Quality: Ensures critical code paths are tested, belittle the risk of bugs in young areas.
- Identify Gaps: Highlight your application & # 8217; s untested lines, map, or branches.
- Better Confidence in Releases: Ensures your test suite properly covers your app ’ s logic before deployment.
- Supports Test-Driven Development (TDD): Encourages writing tryout that align nearly with feature development.
- Optimized Testing Efforts: Helps avoid redundant or ineffective tests by showing which area are already well-covered.
- Visual Feedback: Generates easy-to-read reports that help teams monitor and improve trial coverage over time.
Setting up Code Coverage in Cypress
It takes three steps to set up Cypress codification coverage:
- To find out which statements are being fulfill, firstlyinstrument codification.
- For those statements to be execute,run the instrumented codification.
- Report the solventand see the execution, if any.
1. Instrumentation
The instrumentation procedure includes the following steps: calculating the number of lines of source code that were executed during testing, parse it to identify all functions, statements, and branches, and ultimately adding counters to the codification. These tabulator designate the frequence of execution of these statements, use, and branches.
// square.js function square (num) {homecoming num * * 2} module.exports = {square}The source codification for instrumenting the code above might resemble this.
const c = (window.__coverage__ = {// we have just one function, thus [0] f: [0], // we receive three statements, thus [0,0,0] s: [0, 0, 0],})For our program, let & # 8217; s make a test.
// square.spec.js const {square} = require ('./square ') it ('squares a number ', () = & gt; {expect (square (5)) .to.equal (25)})The aforesaid test will add counters to the reporting object that may resemble this.
const c = (window.__coverage__ = {f: [1], s: [1, 1, 1]}) // Our function is defined in the first statement, which is incremented. c.s [0] ++ function square (num) {c.f [0] ++ c.s [1] ++ homecoming num * * 2} // 3rd statement is phone and incremented as well c.s [2] ++ module.exports = {square}- In this instance, our test extend 100 % of the code.
- The created report for this coverage object will be preserved in a human-readable format.
- Cypress does not instrumentate our code; instead, we must do so manually using either the nyc or the babel-plugin-istanbul as part of the codification translation pipeline (a command-line interface to istanbul).
2. Installation & amp; Configuration
- Let & # 8217; s instal and set up each of our required dependance.
- You can instrumentate your codification with Istanbul coverage using the babel plugin& # 8220; babel-plugin-istanbul. & # 8221; It is compatible with Karma and Mocha (which is apply by Cypress as easily)
- A coverage information summary API is usable from istanbul-lib-coverage, which can read and integrate coverage data.
- An HTML file is one of the several output formats for a code coverage study from the Istanbul command line interface nyc.
sh $ yarn add babel-plugin-istanbul istanbul-lib-coverage nyc
Install the Cypress Code Coverage Plugin
sh $ yarn add cypress @ cypress/code-coverage
Configure.babelrc (if you don & # 8217; t already have one, create one)
{'' plugins '': [`` istanbul '']}Make a nyc contour file. In this instance, I want to examine the coverage for both.js and .vue
For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.
{'' extension '': [`` .js '', `` .vue '']}3. Setup for the Cypress Code Coverage Plugin
To use the Cypress Code Coverage plugin after lend Cypress to your project, you must configure the Cypress plugin file, located atcypress/plugin/index.js.
importee ' @ cypress/code-coverage/support '
module.exports = (on, config) = & gt; {on ('task ', expect (' @ cypress/code-coverage/task '))}Let & # 8217; s take a clip to ponder some philosophic thought now that everything is set up. Should we try to extend everything? Though it may seem wonderful, achieving 100 % codification reporting does not imply that we are bug-free.
You & # 8217; ll see that this test contains zero assertions:
it ('generates a random fact ', () = & gt; {cy .visit ('/ ') cy .get ('button ') .click ()});However, there are many things that might go wrong in our app. Any number of things may go improper, include our layout, improper character interpretation, and a malfunctioning API. Nevertheless, our test extend every potential scenario.
Running through the app doesn ’ t truly assert the values it revert. This is something to abide in brain when writing tests that incorporate test reportage.
- Finding areas of a labor that are not covered by tests and navigating it can be made easy using code coverage.
- It is an excellent navigational puppet that is quick to set up and offers many benefits.
The image below show extra counters and instructions that should be present in the JavaScript resources of your application if it has been decent instrumented.
When watch the & # 8220; Application under exam iframe, & # 8221; you will notice the window.__coverage__ objective.
If you have instrumented the code for your application and saw the window. __coverage__ object, this plugin will save the coverage into the.nyc_output folder and generate story once the exam have been completed (even in the interactive mode). The brochure coverage/lcov-report comprise the LCOV and HTML report.
How to Merge Code Coverage from Parallel Tests
When running Cypress exam in analog, each instance generates its own codification coverage story. You need to merge these individual report into a single coverage summary to get a unified view. Here & # 8217; s how to do it:
Step 1: Install Required Packages
Make sure establish these tools:
npm install nyc @ cypress/code-coverage -- save-dev
Step 2: Save Coverage Outputs per Machine
Make sure each run saves its.nyc_output brochure(usually generate in your project root) as an artifact or partake folder.
Step 3: Merge .nyc_output Folders
After all parallel runs complete, gather all.nyc_output foldersinto one localisation. For example, in your CI pipeline, you might do:
mkdir -p merged_output/.nyc_output cp * /.nyc_output/ * merged_output/.nyc_output/
Step 4: Generate Merged Report
Once the files are merged, run the next bidding in the incorporated directory.
nyc report -- reporter=html
Step 5: Upload to Coverage Tools
This is an optional pace. You can likewise upload the incorporate results to.
What is UI Coverage in Cypress?
UI reporting in Cypress refers to tracking how much of the exploiter interface (UI) component are interacted with or exert during.
It helps answer questions like:
- Are all important blind or user flowing tested?
- Are critical elements (e.g., submit button, modal) interacted with?
- Do your tryout feign real user behavior across the UI?
While Cypress doesn ’ t offer built-in UI coverage tracking, it can be estimated with tradition logging, plugins, or that monitor element interaction and page coverage during test execution.
Code Coverage vs UI Coverage
Unlike codification coverage, which measures how much of the application ’ s source codification is executed, UI coverage centre on whether key UI factor (like push, pattern, etc.) are actually call, clicked, or examine in your test retinue.
| Aspect | Code Coverage | UI Coverage |
|---|---|---|
| What it Measures | How much of the application ’ s origin code is run during tests | How much of the user interface (UI) is interacted with during examination |
| Focus | Backend logic, functions, conditions, and argument | Screens, buttons, forms, links, and user flow |
| Purpose | Ensures your code is be screen | Ensures the UI behaves correctly under user interaction |
| Tools Used | @ cypress/code-coverage, Istanbul (nyc) | Custom logging, visual testing tools, Cypress commands |
| Output | Detailed reports testify which parts of codification were executed | Insights into which UI elements were tested or left untouched |
| Common Use Case | Validating logic reportage in APIs or app internals | Verifying that critical user interactions are test |
App vs Unit Tests
A web application needs to be instrumented. This means that you should instrument the requests for index.html whenever the test uses the cy.visit (& # 8216; localhost:3000 & # 8217;) function. Often, you need to add the babel-plugin-istanbul to your pipeline someplace.
is try case-by-case functions from your covering code by importing them straight into Cypress spec files. Cypress can instrument this summons for you. Check out the section oninstrument unit tests.
- The coverage folder contains solvent in various sort, and the raw coverage datum is kept in the.nyc_output folder.
- The coverage statistics are useable for your review.
- Since nyc is subordinate on this plugin, it should be forthwith accessible.
Here are a few typical instances:
# see just the coverage compendious $ npx nyc study -- reporter=text-summary # see but the reporting file by file $ npx nyc report -- reporter=text # save the HTML report again $ npx nyc report -- reporter=lcov
Why Run Cypress Tests on BrowserStack
BrowserStack is a cloud-based testing program that permit you run Cypress exam efficiently across multiple device-OS-browser combinations. Here are a few reason why you should choose BrowserStack:
- : Cypress runs on circumscribed browser, mainly Chrome-based ones. BrowserStack helps you expand your Cypress trial to many other browser, such as Safari, Edge, IE, and more.
- Video Recording: The power to record videos of test execution is a significant benefit of utilise BrowserStack to execute Cypress tests.
- Cloud Infrastructure: This cloud-based program does not require setting up or maintaining browser or physical devices locally.
- Parallel Testing: With, you can run multiple Cypress examination concurrently, speed up examination execution and eventually the release cycles.
- Real-device examination: BrowserStack volunteer you a immense, letting you run Cypress tests on 3500+ real device, browser, and OS combinations, thus grant you to test under.
- Integrations: BrowserStack offers seamless s with respective like, Circle CI, Bamboo and more.
- Scalability: BrowserStack supports real-device and parallel testing on a cloud-based substructure, enabling you to run hundreds of Cypress tests across different surround.
Conclusion
This clause learn you how to give codification coverage from local E2E tests and use the nyc dictation to produce story in various formats. This can be integrated into your CI system to monitor reportage trends well.
It aid you negociate better and gain confidence in your product ’ s quality, by ameliorate code quality.
For scalable machine-driven testing, use BrowserStack, which runs test without change your scripts. With Parallel Testing, you can test across multiple browsers and devices faster.
Useful Resources for Cypress
Understanding Cypress
Use Cases
Tool Comparisons
On This Page
- What is Code Coverage in Cypress?
- Importance of Cypress Code Coverage
- Benefits of Code Coverage in Cypress
- Setting up Code Coverage in Cypress
- How to Merge Code Coverage from Parallel Tests
- What is UI Coverage in Cypress?
- Code Coverage vs UI Coverage
- App vs Unit Tests
- Why Run Cypress Tests on BrowserStack
- Useful Resources for Cypress
# Ask-and-Contributeabout this subject with our Discord community.
Related Guides
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free