How to Perform Screenshot Testing in Cypress
On This Page What is Screenshot Testing?What is Cypress Screenshot?
- What is Screenshot Testing?
- What is Cypress Screenshot?
- Syntax for Cypress Screenshot
- Naming Conventions used for Cypress screenshots
- Types of Snapshots in Cypress
- Prerequisites for Cypress Snapshot Testing
- How to Perform Screenshot Testing using Cypress
- Good practices for Screenshot Testing
- How BrowserStack Enhances Cypress Screenshot Testing
- Useful Resources for Cypress
How to Perform Screenshot Testing in Cypress
Cypress provides built‑in support for capturing screenshots and DOM snapshots during test runs. These tools help you detect unexpected changes to your application ’ s layout or structure as your codification evolves. It likewise helps spot visual or structural fixation and maintain a more stable trial rooms.
This guide will explore how engineers can leverage screenshot screen in Cypress to raise test stability, debugging, and overall tryout effectiveness.
What is Screenshot Testing?
involves beguile a snapshot of a web page or application at a specific point in time. This screenshot is so expend to compare against the expected result during future test runs. The purpose is to verify if the optic appearance of element on the screen is consistent and matches the expected result.
For example, guess test a table on a webpage. A screenshot of the table is captured, and its contents are verified against the provided data. In future test tally, this captured screenshot is compared with the current screenshot to ensure the content hasn & # 8217; t modify, without have to manually check the details every time.
Key Benefits of Screenshot Testing:
- Eliminates Repetitive Verification: Screenshot testing removes the need for testers to manually equate the expected and actual results in each iteration. It automates the process of verifying visual elements, saving time and exploit.
- Easier Comparisons: Instead of manually copying and pasting results for comparison, screenshots offer a visual reference. This method meliorate the clarity and accuracy of comparison by instantly highlighting any differences.
- Efficient Testing for Large Applications: For large, complex applications, manually verifying test results can be eat. Screenshot essay simplifies the summons by automating the comparison and rivet on key visual view.
Types of Screenshot Tests:
- DOM Snapshot Testing: This captures a screenshot of the Document Object Model (DOM) when the real results are charge. It grant testers to inspect both the UI constituent and the underlying code for divergence.
- Component Snapshot Testing: This method captures the province and contents of specific UI part being prove. By store these snapshots in a central repository, testers can rapidly compare current test results with the quotation images for fast, accurate results.
- Updating Snapshots: Screenshots need to be updated whenever there are modification to the UI or test flowing. Whenever the expected results are change or a new testing scenario is acquaint, the snapshots should be reviewed and update consequently to reflect the new expectations.
Also Read:
What is Cypress Screenshot?
In, a screenshot is an image charm the browser & # 8217; s screen at a specific minute during trial performance. Cypress has built-in functionality to automatically capture screenshots, regardless of whether the examination is run in interactional mode (usingcypress open) or headless mode (utilizecypress runor as part of a pipeline).
The tool is designed to take screenshots automatically when a test fails without postulate any extra code. This feature simplifies debugging by providing visual grounds of the application & # 8217; s state at the clip of failure.
Also Read:
Syntax for Cypress Screenshot
Cypress supply a built‑in screenshot () method that can be telephone either as a chainable command or as a global command. Below is the syntax for each.
As a Chainable Command
.screenshot () .screenshot (fileName) .screenshot (options) .screenshot (fileName, options)
As a Global Command
cy.screenshot () cy.screenshot (fileName) cy.screenshot (options) cy.screenshot (fileName, alternative)
Each method permit you to capture a screenshot with or without a custom filename and with optional scene.
Naming Conventions used for Cypress screenshots
Cypress follows specific nonremittal naming formula when save screenshots. These conventions help in organise screenshots effectively, particularly when dealing with multiple tests and footrace. Here are the key naming figure used by Cypress:
- Default Screenshot Naming: By default, screenshots are saved with a path relative to the screenshots folder, follow by the spec file fix, and the trial suite and test gens. The format looks like:
{screenshotsFolder} / {specPath} / {testName} .png- Custom Screenshot Naming: If a usance gens is supply for the screenshot, that name is used rather of the default test retinue and test gens. The format for a named screenshot is:
{screenshotsFolder} / {specPath} / {name} .png- Handling Duplicate Screenshots: For duplicate screenshots, Cypress tack a number to secern them. The initiatory duplicate screenshot will be named like this:
{screenshotsFolder} / {specPath} / {testName} (1) .png- Failure Screenshot Naming: When a examination fails, Cypress automatically adds & # 8220; (failed) & # 8221; to the screenshot & # 8217; s name, using the nonremittal naming convention. The screenshot format in causa of failure looks like:
{screenshotsFolder} / {specPath} / {testName} (failed) .pngTypes of Snapshots in Cypress
Cypress supports two type of snapshots. These approaches serve different testing needs and help you understand how your coating changes over clip.
1. DOM Snapshots
DOM snapshot capture the construction and province of your page at a specific point during a examination. These snapshots are created using the @ cypress/snapshot plugin. Instead of capturing an image, this method saves the HTML and schoolbook of the element or page.
It allows you to compare its construction between test runs. This is specially useful for verifying that elements, textbook, and structure remain unchanged across exam executions.
2. Image-Based Snapshots
Image-based snap are captured using the built‑in cy.screenshot () method in Cypress. These snapshots save an existent image of the page or element and are ideal for identifying visual changes such as layout transmutation, font changes, or unexpected rendition issues.
Prerequisites for Cypress Snapshot Testing
Before you can capture screenshots in Cypress, make sure you receive the following in place:
- Install Cypress:Install Cypress as a development dependency if it ’ s not already bestow to your undertaking:
npm install cypress -- save-dev
- Set Up a Test Project:Ensure you have a working Cypress project configured. This includes a cypress.config.js or cypress.json file and a cypress directory with test files.
- Familiarity with the cy.screenshot () Command:Understand the syntax and options available for capturing screenshots, such as filename and settings like blackout, magazine, or capture.
- Have a Page or Element to Test:Identify a page or specific element you need to bewitch. This allows you to write focussed and meaningful screenshot test.
How to Perform Screenshot Testing using Cypress
Cypress offers several ways to capture screenshots depending on your screen needs. You can capture an total page, place a specific element, customise filenames, use built‑in choice, and yet save screenshots for visual comparisons. Here are the almost mutual methods:
1. Capturing a Full Page Screenshot
Cypress can capture the total page as it seem during test execution.
Example: The following test captures a full-page screenshot of the BrowserStack demo website.
it ('Captures a full page screenshot ', () = & gt; {cy.visit ('https: //bstackdemo.com/ '); cy.screenshot ();});This command captures a screenshot of the page as it appears and saves it to the cypress/screenshots directory.
SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.
2. Capturing a Specific Element
Cypress allows capturing solely a specific ingredient by select it foremost.
Example:This test catch a screenshot of the Sign In button.
it ('Captures a specific ingredient screenshot ', () = & gt; {cy.visit ('https: //bstackdemo.com/ '); cy.get (' # signin ') .screenshot ();});This command capture only the#signinconstituent and save the screenshot as an icon.
3. Using cy.screenshot () for Custom Filenames
Cypress supports custom names for screenshots, create them leisurely to locate and survey.
Example: The test captures the Sign In button and saves the screenshot with a custom filename.
it ('Captures a screenshot with a usage filename ', () = & gt; {cy.visit ('https: //bstackdemo.com/ '); cy.get (' # signin ') .screenshot ('sign_in_button ');});This command save the screenshot of the Sign In push as sign_in_button.png in the screenshots directory.
4. Using Screenshot Options
Cypress furnish advanced options like blackout, seizure, and scale to give users more control over screenshots. These options can be expend individually or combined, depending on the test requirements.
Option 1: dimout
This option permit certain elements to be enshroud when capturing a screenshot.
Example:
it ('Captures a screenshot with a blacked out element ', () = & gt; {cy.visit ('https: //bstackdemo.com/ '); cy.screenshot ({blackout: [' # header ']});});The #headercomponent is hidden from the screenshot, make it ideal for ignoring dynamic or irrelevant section.
Option 2: capture
This option define the country of the page to capture. It can be set to viewport (visible area) or fullPage.
Example:
it ('Captures only the viewport area ', () = & gt; {cy.visit ('https: //bstackdemo.com/ '); cy.screenshot ({seizure: 'viewport '});});This captures only the seeable area of the page (without scroll) and makes the screenshot focused and concise.
Option 3: scale
This option increases the pixel density of the screenshot, making it crisp and suitable for revaluation on high‑resolution displays.
Example:
it ('Captures a scaled screenshot ', () = & gt; {cy.visit ('https: //bstackdemo.com/ '); cy.screenshot ({scale: true});});This catch a higher‑quality page adaptation and is ideal for comparing subtle pattern changes.
5. Capturing Screenshots for Behavioral Changes
Screenshot examination can also be used to confirm visual changes induce by user interaction.
Example:This test captures a screenshot after clicking the Sign In button.
it ('Captures a screenshot after an interaction ', () = & gt; {cy.visit ('https: //bstackdemo.com/ '); cy.get (' # signin ') .click (); cy.screenshot ('after_sign_in_click ');});This command captures the page state after clicking the Sign In button, do it easy to survey changes resulting from the interaction.
6. Running the Test and Viewing Results
Tests can be run in Cypress, and the results can be reviewed in the screenshots directory.
Example:The command below runs the test and saves screenshots to the cypress/screenshots directory.
npx cypress run
This command executes the exam in headless mode, bewitch screenshots, and saves them in the cypress/screenshots directory for critique.
Best practices for Screenshot Testing
Here are some best practices to ensure accurate and efficient screenshot examination:
- Verify the shot: Ensure that the captured screenshot meets the expected criteria before move with further try. This pace is crucial to confirming the test & # 8217; s lustiness.
- Update snapshots regularly: Always update snapshots when there are changes in the testing flows or scenario. This helps in maintaining accurate references for future exam and avoiding failures due to outdated snapshots.
- Track alteration in expected results: If the expected results change, update the snapshots accordingly. This ensures that the essay process remains aligned with the current coating province.
- Utilize testing tools effectively: Platforms like BrowserStack allow leisurely execution of screenshot testing, reduce clip and endeavor. Combining snapshot test with Cypress enhances test accuracy and helps find issues earlier.
- Ensure iterative test success: By keeping snapshots updated, iterative testing becomes more effectual in finding and settle quality subject in the application.
How BrowserStack Enhances Cypress Screenshot Testing
BrowserStack is a cloud-based testing platform that enables Cypress tests to be fulfil on existent browsers and devices over the internet. It captures screenshots, videos, logs, and other artifact directly within its fascia, get it ideal for cross-browser ocular testing and debugging.
Here ’ s how to use for Cypress examination.
1. Install BrowserStack CLI
Install the BrowserStack Cypress CLI, which links your local Cypress setup to the cloud:
npm install -g browserstack-cypress-cli
This command provides accession to commands like browserstack-cypress init and run& # 8211; sync
2. Initialize Configuration
Generate a baseline browserstack.json file in your project root:
browserstack-cypress init
This file include placeholders for your BrowserStack username, access_key, target browsers, and former necessitate scene.
3. Update browserstack.json
Open the file and edit the placeholders:
{'' auth '': {'' username '': `` YOUR_USERNAME '', '' access_key '': `` YOUR_ACCESS_KEY ''}, '' browsers '': [{`` browser '': `` chrome '', `` os '': `` Windows 10 '', `` versions '': [`` modish '']}, {`` browser '': `` firefox '', `` os '': `` OS X Mojave '', `` edition '': [`` latest '']}], '' run_settings '': {'' cypress_config_file '': `` cypress.config.js '', '' project_name '': `` Your Project Name '', '' build_name '': `` Build # 1 '', '' parallels '': 3}}Note: Add or change browser entries and adjust parallels to gibe your test program.
4. Serve Your Application
Ensure your app is running locally before spark tests:
npm start
By default, BrowserStack connects to port 3000, or update your config to match your server.
5. Execute Cypress on BrowserStack
Run your tests on the cloud with screenshots and logs automatically contemporise:
browserstack-cypress run -- sync
This command runs exam remotely, capture screenshots and picture, and syncs artifact to your local build_artifacts folder.
6. View Dashboard Results
On BrowserStack ’ s Automate dashboard:
- Open a test session
- Navigate to theScreenshotstab to view captured images
- Watch recorded picture and logarithm
- Examine timestamps and browser metadata
7. (Optional) Run Tests Locally
To preview screenshots before launching cloud tests, execute tests locally via Cypress:
npx cypress open
Run spec files like screenshot_full_spec.js, screenshot_element_spec.js, or screenshot_options_spec.js, and inspect screenshots in cypress/screenshots.
Conclusion
Cypress screenshot testing makes it straightforward to charm and critique an application & # 8217; s optic province. By using built‑in methods like cy.screenshot () and leverage its options, you can espy layout change, humiliated elements, and unexpected behavior across test runs.
With, Cypress screenshot tests can be take beyond the local environs. It give admittance to over 3,500+ real browsers and device. This do it easy to run Cypress screenshot testing at scale and review results in a central, cloud‑based dashboard.
Useful Resources for Cypress
Understanding Cypress
Use Cases
Tool Comparisons
On This Page
- What is Screenshot Testing?
- What is Cypress Screenshot?
- Syntax for Cypress Screenshot
- Naming Conventions used for Cypress screenshots
- Types of Snapshots in Cypress
- Prerequisites for Cypress Snapshot Testing
- How to Perform Screenshot Testing expend Cypress
- Best practices for Screenshot Testing
- How BrowserStack Enhances Cypress Screenshot 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