How to Perform Visual Testing for Components in Cypress
What is Visual Component Testing in Cypress?
- What is Visual Component Testing in Cypress?
- Steps to Perform Visual Component Testing in Cypress
- Step 1: Install Cypress to your project
- Step 2: Unfastened Cypress
- Step 3: Configure Cypress Component Testing
- Step 4: Install the cypress-image-diff-js plugin
- Step 5: Configure the Image Diff software
- Step 6: Configure the Support file
- Optional Step: Create Simple React Component
- Step 7: Create Visual Test for Component
- Step 8: Execute the test
- Cypress Component Visual Testing use Percy
- Why Use Percy for Cypress Component Tests?
- Better Practices for Cypress Visual Testing
- Useful Resources for Cypress
How to Perform Visual Testing for Components in Cypress
Cypress makes it easy to test UI components in isolation and validate their behavior immediately in the browser. Visual constituent testing in Cypress mountain a component, captures a screenshot, and equate it with a baseline to get visual regressions. Using a cloud service like BrowserStack Percy, these snapshots are process with an AI engine that filter noise and flags solely meaningful UI deviation.
Overview
How to Perform Visual Component Testing in Cypress?
Step 1: Install Cypress:
npm install cypress -D
Step 2: Open Cypress Test Runner:
npx cypress unfastened
Step 3: Configure Cypress for Component Testing:Set componentconfiguration incypress.config.js
Step 4: Install Visual Diff Plugin:
npm i cypress-image-diff-js
Step 5: Configure Plugin and Support File:
Import the visual diff plugin in your Cypress config and enable its snapshot command in the support file so Cypress can liken component screenshots during tests.
Step 6: Write a Optical Component Test:
import {mount} from 'cypress/react '; import DemoComponent from ' .. / .. /src/DemoComponent '; describe ('Demo Component ', () = & gt; {it ('renders visually ', () = & gt; {mount (& lt; DemoComponent / & gt;); cy.get (' [data-testid=demoButton] ') .should ('contain.text ', 'Demo Component Button '); cy.compareSnapshot ('component-testing ', 0.2);});});
Step 7: Run the Test:
npx cypress run -- component
Step 8: Use Percy for Cloud Visual Testing:
Integrate Percy into your Cypress setup to capture AI-enhanced cloud snapshots and mechanically notice meaningful visual regressions across browsers and viewports.
This guide explains how to set up and run visual component testing in Cypress.
What is Visual Component Testing in Cypress?
Visual in focuses on verify the visual appearing and layout of individual within an covering. This ensures that components render correctly and systematically across different state even after codification changes, foreclose
This operation incorporate Cypress ’ s component testing capabilities with image diffing tools like Cypress Image Diff or platform such as to compare component snapshots before and after alteration, making it easy to spot regression early in maturation cycles. This helps ensure that component conduct and appearing remain consistent across updates, peculiarly in modern frameworks such as React, Angular, and Vue.
Must Read:
Steps to Perform Visual Component Testing in Cypress
Below are the measure to get ocular ingredient testing running in your project.
Pre-requisites
Before proceeding, ensure you have a development framework such as React, Angular, or VueJS set up as a requirement.
Also Read:
Below are the key steps to execute Visual Testing in Cypress
Step 1: Install Cypress to your task
Using the command
npm install cypress -D
Step 2: Open Cypress
Exposed Cypress with command
npx cypress open
The above bid will create the default directory construction for Cypress tests.
Step 3: Configure Cypress Component Testing
- Once you exposed Cypress, you will see the window, E2E and Component Testing.
- Choose Component Testing.
- Using the on-screen instruction, configure your project with Cypress Component Testing.
Step 4: Install the cypress-image-diff-js plugin
For the Visual Testing, you need toinstall cypress-image-diff-js, Use the below bidding to install the image equivalence node package.
npm i cypress-image-diff-js
Step 5: Configure the Image Diff package
Navigate to yourcypress.config.jsusually locate in your root project.
Import the cypress-image-diff-js/dist/plugin into your config file as shown below.
const setupNodeEvents = require ('cypress-image-diff-js/dist/plugin ')Navigate to component subdivision in cypress.config.js file add the setupNodeEvents
The total cypress.config.js file looks like below.
const {defineConfig} = require (`` cypress ''); const setupNodeEvents = require ('cypress-image-diff-js/dist/plugin ') module.exports = defineConfig ({factor: {devServer: {framework: 'react ', bundler: 'vite ',}, setupNodeEvents}, e2e: {}});Step 6: Configure the Support file
Navigate to cypress/support/component.js and add the below code
const compareSnapshotCommand = require ('cypress-image-diff-js/dist/command ') compareSnapshotCommand ()Ensure that import & # 8216; ./commands & # 8217;, is already present in the component.js file, if it doesn & # 8217; t exist, then add it.
Optional Step: Create Simple React Component
This step is optional, if you are already having a component make so you can skip this step.
For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.
Below is the sample constituent make for Demo Purpose
We have created DemoComponent.jsx in my-react-app/src folder
The code seem like the below
import {useState} from 'react' import {Button, Alert} from 'react-bootstrap '; import './App.css' significance 'bootstrap/dist/css/bootstrap.min.css '; exportation default purpose DemoComponent () {return (& lt; div & gt; & lt; div & gt; & lt; Button variant= '' master '' size= '' lg '' & gt; Demo Page & lt; /Button & gt; & lt; p & gt; & lt; /p & gt; & lt; /div & gt; & lt; div & gt; & lt; Alert key= '' info '' variant= '' information '' & gt; This is a tryout Alert! & lt; /Alert & gt; & lt; /div & gt; & lt; /div & gt;)}The above is a simple component that has a button and simple alarum like the below.
Step 7: Create Visual Test for Component
Let & # 8217; s create a simple visual exam for the above component,
Navigate to cypress/component folder and create a simple .jsx file name it asvisual-test.jsx
Also Read:
The code looks like the below:
import {mountain} from 'cypress/react' import DemoComponent from ' .. / .. /src/DemoComponent' const demoButton = ' [data-testid=demoButton] ' describe ('Demo Component ', () = & gt; {it ('Visual Testing Cypress ', () = & gt; {climb (& lt; DemoComponent / & gt;) cy.get (demoButton) .should ('contain.text ', 'Demo Component Button ') cy.compareSnapshot ('component-testing ', 0.2)})})- In the above code,mount (& lt; Stepper / & gt;): Mounting DemoCompenent for testing, which is imported using import DemoComponent from & # 8216; .. / .. /src/DemoComponent & # 8217;
- cy.get (demoButton) .should (& # 8216; contain.text & # 8217;, & # 8216; Demo Component Button & # 8217;),: This line is an assertion to ensure that our factor button is supply correctly.
- cy.compareSnapshot (& # 8216; component-testing & # 8217;, 0.2): This line takes the screenshot and compares it against the base screenshot, 0.2 is the threshold which is the tolerance of pixel conflict of the screenshot.
Step 8: Execute the test
You can execute the Cypress examination, using both the command line and Cypress Test Runner window.
Using the Cypress Test Runner window
- Use npx cypress open command
- Choose the Component Testing and Browser
- Click on the examination name in our instance it isvisual-test.cy.jsx
- Once you execute the exam, Cypress shows the output pass or fail
- For cypress CLI executionyou can use the below dictation
npx cypress run –component
Note: You need to execute the test at least two multiplication, the 1st run captures the base screenshot, and the subsequent run captures the genuine screenshot and compares it against the base screenshot.
In our cause there was no departure, so tests are label as passes.
Let & # 8217; s modify the component by changing the push background color from blue to red
Execute the examination again.
You can see that the test has failed since there is a deviation between the foot screenshot and the actual screenshot.
You can reckon the dispute, by sail to thedifffolder under thecypress-visual-screenshots folder
Cypress Component Visual Testing using Percy
The is the most popular cloud based optic testing tool. Percy provides a dedicated splasher to compare the visual differences. One of the unique features of Percy is you can visually check how the components are supply across multiple browsers such as Edge, Chrome, Safari, etc. Percy ply a feature to accept, and reject the changes.
Use Step 1 to Step 3 to configure Cypress to your undertaking, after that follow the below instructions
Install Percy for Cypress
- Using the command below install Percy for Cypress
npm install -- save-dev @ percy/cli @ percy/cypress
- Configure cypress/supportfolder
Navigate to cypress/support/command.js file and add the importation argument
import ' @ percy/cypress ';
Create a component(Optional, if you have already created a simple component omission this stride). Below is a elementary react part to test the Percy visual testing.
importation {useState} from 'react' import {Button, Alert} from 'react-bootstrap '; import './App.css' meaning 'bootstrap/dist/css/bootstrap.min.css '; exportation default function DemoComponent () {//style= {{background: `` red ''}} return (& lt; div & gt; & lt; div & gt; & lt; Button variant= '' primary '' size= '' lg '' & gt; Demo Component Button & lt; /Button & gt; & lt; p & gt; & lt; /p & gt; & lt; /div & gt; & lt; div & gt; & lt; Alert key= '' info '' variant= '' information '' & gt; This is a test Alert! & lt; /Alert & gt; & lt; /div & gt; & lt; /div & gt;)}- Write a unproblematic Percy Visual Test for Component employ Cypress
- Navigate to cypress/component folder create avisual-test.cy.jsxfile
import {mount} from 'cypress/react' import DemoComponent from ' .. / .. /src/DemoComponent' const demoButton = ' [data-testid=demoButton] ' describe ('Demo Component Testing Percy ', () = & gt; {it ('Visual Testing Cypress Percy ', () = & gt; {mount (& lt; DemoComponent / & gt;) cy.get (demoButton) .should ('contain.text ', 'Demo Component Button ') cy.percySnapshot ('percy-component-visual-test ');})})In the above codification,
- mount (& lt; Stepper / & gt;):Mounts the DemoCompenent for testing, which is imported using import DemoComponent from & # 8216; .. / .. /src/DemoComponent & # 8217;
- cy.get (demoButton) .should (& # 8216; contain.text & # 8217;, & # 8216; Demo Component Button & # 8217;): This line is an assertion to ensure that our component button is render correctly.
- cy.percySnapshot ();: This is a Percy command to direct the DOM shot and then Percy CLI uploads the snapshots to the Percy fascia.
Set the PERCY_TOKEN Environment Variable:
- Navigate to Percy Project. Refer to thissupporter certificationto cognise more.
Copy the PERCY_TOKEN.Read more.
Set the Environment Variable # Unix $ export PERCY_TOKEN= '' & lt; your-project-token & gt; '' # Windows $ set PERCY_TOKEN= '' & lt; your-project-token & gt; '' # Powershell $ $ Env: PERCY_TOKEN= '' & lt; your-project-token & gt; ''
Read More:
Run Component Tests using Percy Cypress
npx percy exec -- cypress run –component
Once the execution is consummate, the command line yield will have the Percy anatomy URL, you can navigate to the build URL to check the difference.
Note: you need to execute the Percy trial at least two time to check the answer, as you need to have a base screenshot and an actual screenshot to liken.
If there are no changes so Percy show & # 8220; No Changes. & # 8221;
Let & # 8217; s modify our code, alter the button background vividness to Red from Blue and execute the test again.
You can see in the above persona, that the departure is shown side by side.
Why Use Percy for Cypress Component Tests?
are cognize to validate functionality, ensuring visual consistency across browsers, device, yet it can get challenging using local screenshot compare alone for the same purpose. Percy strengthen this workflow by providing true, AI-powered visual regression screen that integrates directly into your existing Cypress setup.
- AI-Stabilized Snapshots:Percy ’ s filters out noise from animations, rendering difference, and dynamic datum. This facilitate reduce false positives, which is one of the virtually common matter in component-level optical testing.
- Cross-Browser & amp; Responsive Rendering:Cypress typically runs component tests in a single browser, but UI regressions ofttimes appear alone in specific browsers or viewports. Percy captures each component snapshot across multiple browsers and breadth, ensuring that your UI stays consistent everywhere.
- AI-Assisted Visual Review:Percy ’ s highlights meaningful UI changes, supply open summaries, and speeds up the reappraisal process so squad can quick understand and sanction visual updates.
- CI/CD-Friendly Scaling:Percy go seamlessly into modern CI pipelines. Automated baselines, parallel render, and status checks help team notice optic regression betimes and ship component updates with sureness.
Pricing
- Free Plan: Available with up to 5,000 screenshots per month, ideal for go started or for small projection.
- Paid Plan: Starting at $ 199 for innovative lineament, with custom pricing available for enterprise plan.
Best Practices for Cypress Visual Testing
Adopting best practices ensures the reliability and efficiency of your visual tests. Here are some key guidepost to follow:
- Identify the Need for Visual Testing: Use visual examination when UI appearing is critical or when end-to-end tests rely heavily on verifying style belongings like visibility, coloring, and layout.
- Ensure the Application is Fully Loaded: Capture visual snapshot simply after confirming that all dynamic substance, animations, and rendering processes are complete.
- Standardize Timestamps: Freeze timestamps during tests to conserve consistency in visual outputs, especially for part exhibit date or time-sensitive information.
- Control Application State: Use consistent test data and mock outside dependencies to ensure the covering behaves predictably during visual examination.
- Focus on Targeted Elements: Test individual components or specific sections of the UI to avoid unrelated changes touch the solvent.
- Combine with: Perform visual testing alongside component testing to validate the appearing and functionality of individual UI constituent in isolation.
- Update Snapshots Strategically: Regularly review and update snapshots to meditate intentional UI alteration while avoiding unnecessary updates that could mask regressions.
- Integrate Visual Tests with: Include visual testing in uninterrupted consolidation grapevine to get regressions early and maintain consistent visual quality across release.
Conclusion
The mod development framework further the growing of the factor in isolation. Visual Testing is the most democratic method for testing the Visual Changes in UI. Cypress and Percy make the ocular testing lots easier and efficaciously bring the visual testing to the component level. The component-level visual testing helps faster development.
Useful Resources for Cypress
Understanding Cypress
Use Cases
Tool Comparisons
On This Page
- What is Visual Component Testing in Cypress?
- Steps to Perform Visual Component Testing in Cypress
- Step 1: Install Cypress to your projection
- Step 2: Open Cypress
- Step 3: Configure Cypress Component Testing
- Step 4: Install the cypress-image-diff-js plugin
- Step 5: Configure the Image Diff package
- Step 6: Configure the Support file
- Optional Step: Create Simple React Component
- Step 7: Create Visual Test for Component
- Step 8: Execute the test
- Cypress Component Visual Testing apply Percy
- Why Use Percy for Cypress Component Tests?
- Good Practices for Cypress Visual Testing
- Useful Resources for Cypress
# Ask-and-Contributeabout this topic 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