0
0
Cypresstesting~15 mins

Screenshot capture (cy.screenshot) in Cypress - Deep Dive

Choose your learning style9 modes available
Overview - Screenshot capture (cy.screenshot)
What is it?
Screenshot capture with cy.screenshot is a way to take pictures of your web page during automated tests using Cypress. It helps you save the current view of the page or specific elements as image files. These images can be used to check if the page looks right or to find problems later.
Why it matters
Without screenshot capture, it is hard to see what went wrong when a test fails, especially for visual bugs. Screenshots provide a clear picture of the page state at test time, making debugging faster and easier. They also help teams communicate issues clearly and keep records of UI changes.
Where it fits
Before learning cy.screenshot, you should know basic Cypress commands and how to write simple tests. After mastering screenshots, you can explore visual testing tools and advanced debugging techniques that build on capturing page states.
Mental Model
Core Idea
Taking a screenshot in Cypress is like snapping a photo of your web page at a specific moment during a test to save its exact appearance.
Think of it like...
Imagine you are baking a cake and want to remember how it looks at each step. You take photos after mixing, after baking, and after decorating. Similarly, cy.screenshot captures the page at key moments during testing.
┌─────────────────────────────┐
│ Start Test                  │
├─────────────┬───────────────┤
│ Visit Page  │ cy.visit()    │
├─────────────┼───────────────┤
│ Interact    │ cy.click()    │
├─────────────┼───────────────┤
│ Take Photo  │ cy.screenshot()│
├─────────────┼───────────────┤
│ Continue    │ More commands │
└─────────────┴───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is cy.screenshot command
🤔
Concept: Introducing the basic command to take screenshots in Cypress tests.
cy.screenshot() is a simple command that takes a screenshot of the entire visible area of the web page during a test. You just call it where you want to capture the page.
Result
A PNG image file is saved in the Cypress screenshots folder showing the current page view.
Knowing the basic command lets you capture the page state anytime, which is the foundation for visual debugging.
2
FoundationWhere screenshots are saved
🤔
Concept: Understanding the default location and naming of screenshot files.
By default, Cypress saves screenshots in the 'cypress/screenshots' folder inside your project. The file name includes the test file name and the command name or a custom name if provided.
Result
You find image files organized by test files, making it easy to locate screenshots for each test.
Knowing where screenshots go helps you quickly find and review them after test runs.
3
IntermediateTaking screenshots of specific elements
🤔Before reading on: do you think cy.screenshot() can capture only a part of the page or just the whole page? Commit to your answer.
Concept: You can capture screenshots of specific page elements, not just the whole page.
Instead of cy.screenshot() alone, you can chain it to a selector like cy.get('button').screenshot() to capture only that button's image.
Result
The saved screenshot shows only the selected element, not the entire page.
Capturing specific elements helps focus on parts of the UI that matter, reducing noise and file size.
4
IntermediateCustomizing screenshot file names
🤔Before reading on: do you think you can name screenshots yourself or Cypress always names them automatically? Commit to your answer.
Concept: You can provide custom names to screenshots for better organization.
Use cy.screenshot('my-custom-name') to save the screenshot with a meaningful file name instead of the default one.
Result
The screenshot file is saved with the custom name you gave, making it easier to identify.
Custom names improve clarity when reviewing many screenshots from different tests.
5
IntermediateTaking screenshots on test failure automatically
🤔Before reading on: do you think Cypress takes screenshots automatically when tests fail, or do you have to add code for that? Commit to your answer.
Concept: Cypress can be configured to capture screenshots automatically when a test fails.
In cypress.config.js, set 'screenshotOnRunFailure: true' to enable automatic screenshots on failure. This helps catch the page state at the moment of failure without extra code.
Result
When a test fails, Cypress saves a screenshot automatically with a special name indicating failure.
Automatic failure screenshots save time and ensure you never miss visual evidence of bugs.
6
AdvancedControlling screenshot behavior with options
🤔Before reading on: do you think cy.screenshot() accepts options to control image quality or capture area? Commit to your answer.
Concept: cy.screenshot() accepts options to customize how screenshots are taken, like image quality, blackout areas, or capture mode.
You can pass an options object, e.g., cy.screenshot({ blackout: ['.password'], capture: 'viewport', scale: false }) to hide sensitive info, capture only the viewport, or disable scaling.
Result
The screenshot respects the options, hiding elements or changing image properties as specified.
Options let you tailor screenshots to your needs, improving privacy and relevance.
7
ExpertUsing screenshots for visual regression testing
🤔Before reading on: do you think cy.screenshot alone can detect visual changes over time, or do you need extra tools? Commit to your answer.
Concept: Screenshots can be used with tools to compare images over time and detect UI changes automatically.
By integrating Cypress with visual testing plugins like 'cypress-image-snapshot', you can compare current screenshots with baseline images to find unintended visual changes.
Result
Tests fail if the UI looks different than before, catching visual bugs early.
Combining screenshots with image comparison automates visual quality checks beyond manual review.
Under the Hood
When cy.screenshot() runs, Cypress uses the browser's built-in screenshot API to capture the rendered page or element as a bitmap image. It then saves this image as a PNG file on disk. For element screenshots, Cypress calculates the element's bounding box and crops the image accordingly. Options like blackout overlay CSS to hide elements before capture. The process happens asynchronously during test execution.
Why designed this way?
Cypress designed screenshot capture to be simple and integrated, so testers can easily capture visual states without external tools. Using the browser's native screenshot capabilities ensures accuracy and performance. The flexibility to capture full page or elements and customize options meets diverse testing needs. Automatic failure screenshots help catch bugs without extra effort.
┌───────────────────────────────┐
│ Test runs cy.screenshot()     │
├───────────────┬───────────────┤
│ Browser API   │ Cypress code  │
├───────────────┼───────────────┤
│ Captures page │ Applies options│
│ or element    │ (blackout etc)│
├───────────────┼───────────────┤
│ Returns image │ Saves PNG file│
└───────────────┴───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does cy.screenshot() capture the entire page including parts not visible on screen? Commit yes or no.
Common Belief:cy.screenshot() always captures the full page, even parts you have to scroll to.
Tap to reveal reality
Reality:By default, cy.screenshot() captures only the visible viewport, not the entire scrollable page.
Why it matters:Expecting full page capture can cause missed bugs in hidden areas if you don't scroll or use special options.
Quick: Can you take a screenshot of a specific element by passing a selector string directly to cy.screenshot()? Commit yes or no.
Common Belief:You can do cy.screenshot('selector') to capture an element by selector.
Tap to reveal reality
Reality:cy.screenshot() does not accept selectors; you must first get the element with cy.get('selector').screenshot().
Why it matters:Misusing the API leads to errors or capturing wrong screenshots, wasting debugging time.
Quick: Does Cypress automatically take screenshots on test failure without any configuration? Commit yes or no.
Common Belief:Cypress always takes screenshots on failure by default.
Tap to reveal reality
Reality:You must enable 'screenshotOnRunFailure' in configuration to get automatic failure screenshots.
Why it matters:Assuming automatic screenshots can cause missed visual evidence when tests fail.
Quick: Does cy.screenshot() slow down tests significantly? Commit yes or no.
Common Belief:Taking screenshots always makes tests very slow and should be avoided.
Tap to reveal reality
Reality:While screenshots add some time, Cypress optimizes capture and you can control frequency to balance speed and debugging.
Why it matters:Avoiding screenshots out of fear of slowness can reduce test effectiveness and debugging ability.
Expert Zone
1
Screenshots taken during headless runs may differ visually from headed runs due to rendering differences, so always verify in the intended mode.
2
Blackout option overlays elements with CSS before capture but does not remove them, so layout remains unchanged, preventing false positives in visual tests.
3
Custom screenshot paths can be set via plugins or config, but managing them requires care to avoid overwriting or losing images.
When NOT to use
Avoid relying solely on cy.screenshot for visual regression in large projects; use dedicated visual testing tools like Percy or Applitools that offer advanced diffing and reporting. Also, do not use screenshots for purely functional test assertions where code checks are faster and more reliable.
Production Patterns
In real projects, teams combine cy.screenshot with CI pipelines to capture failure screenshots automatically. They use naming conventions and folder structures to organize images by test suite and run. Visual regression plugins integrate screenshots into baseline comparisons. Screenshots also serve as documentation for UI states during releases.
Connections
Visual Regression Testing
Builds-on
Understanding how to capture screenshots is essential before comparing images to detect UI changes automatically.
Continuous Integration (CI)
Supports
Screenshots integrate with CI pipelines to provide visual evidence of test failures, improving team collaboration and quality.
Photography
Similar process
Just like photography captures moments in time for later review, screenshots freeze the web page state during tests for debugging and analysis.
Common Pitfalls
#1Taking screenshots without scrolling to elements outside the viewport
Wrong approach:cy.get('.footer').screenshot() // footer is off-screen, no scroll
Correct approach:cy.get('.footer').scrollIntoView().screenshot()
Root cause:Not realizing screenshots capture only visible parts, so off-screen elements must be scrolled into view first.
#2Passing selector string directly to cy.screenshot()
Wrong approach:cy.screenshot('.button')
Correct approach:cy.get('.button').screenshot()
Root cause:Misunderstanding that cy.screenshot() is a command on elements, not a selector function.
#3Expecting automatic failure screenshots without enabling config
Wrong approach:// No config set // Tests fail but no screenshots saved
Correct approach:In cypress.config.js: module.exports = { e2e: { screenshotOnRunFailure: true } }
Root cause:Assuming default config enables failure screenshots, missing explicit setup.
Key Takeaways
cy.screenshot captures images of your web page or elements during Cypress tests to help visualize test states.
Screenshots are saved as PNG files in a default folder, but you can customize names and options for clarity and privacy.
You must scroll elements into view before capturing their screenshots to avoid empty or partial images.
Automatic screenshots on test failure require enabling a configuration option to catch bugs without manual effort.
Combining screenshots with visual comparison tools enables powerful automated detection of UI regressions.