Bird
Raised Fist0
Cypresstesting~15 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the primary purpose of using cy.screenshot() in Cypress tests?
easy
A. To capture a picture of the app's current state during a test
B. To pause the test execution
C. To clear the browser cache
D. To simulate user clicks

Solution

  1. Step 1: Understand the function of cy.screenshot()

    This command takes a screenshot of the app at the moment it is called during the test.
  2. Step 2: Compare with other options

    Options B, C, and D describe actions unrelated to capturing images.
  3. Final Answer:

    To capture a picture of the app's current state during a test -> Option A
  4. Quick Check:

    Screenshot = Capture app image [OK]
Hint: Screenshots = pictures of app state during tests [OK]
Common Mistakes:
  • Confusing screenshot with pausing tests
  • Thinking it clears cache
  • Assuming it simulates clicks
2. Which of the following is the correct syntax to take a screenshot with a custom file name in Cypress?
easy
A. cy.screenshot = 'homepage'
B. cy.screenshot: 'homepage'
C. cy.screenshot('homepage')
D. cy.screenshot['homepage']

Solution

  1. Step 1: Recall the correct method call syntax

    In Cypress, methods are called with parentheses and arguments inside, like cy.screenshot('filename').
  2. Step 2: Check each option's syntax

    cy.screenshot('homepage') uses correct function call syntax. Options A, C, and D use invalid JavaScript syntax for method calls.
  3. Final Answer:

    cy.screenshot('homepage') -> Option C
  4. Quick Check:

    Method call uses parentheses [OK]
Hint: Use parentheses to pass file name in cy.screenshot() [OK]
Common Mistakes:
  • Using assignment (=) instead of function call
  • Using colon (:) instead of parentheses
  • Using brackets [] incorrectly
3. Consider this Cypress code snippet:
cy.get('button.submit').click();
cy.screenshot('after-click');

What will happen when this test runs?
medium
A. The test fails because cy.screenshot needs no arguments.
B. The test clicks the submit button but does not take any screenshot.
C. The test takes a screenshot before clicking the button.
D. The test clicks the submit button and saves a screenshot named 'after-click'.

Solution

  1. Step 1: Analyze the code sequence

    The code first clicks the button with class 'submit', then calls cy.screenshot('after-click') to take a screenshot with that name.
  2. Step 2: Understand the effect of cy.screenshot()

    The screenshot is taken after the click, so the file will be named 'after-click'.
  3. Final Answer:

    The test clicks the submit button and saves a screenshot named 'after-click'. -> Option D
  4. Quick Check:

    Click then screenshot with name [OK]
Hint: Commands run in order; screenshot after click saves named image [OK]
Common Mistakes:
  • Thinking screenshot happens before click
  • Believing screenshot requires no arguments
  • Assuming no screenshot is taken
4. You wrote this code:
cy.screenshot('login-page', { capture: 'viewport' });

But the screenshot file is not saved. What is the likely problem?
medium
A. The capture option value is incorrect; it should be 'runner'.
B. The capture option 'viewport' is valid; the problem is elsewhere.
C. The cy.screenshot command must be chained after cy.get().
D. The file name must not have a dash ('-').

Solution

  1. Step 1: Check the capture option values

    Cypress supports 'viewport', 'runner', and 'fullPage' as valid values for capture. 'viewport' is valid.
  2. Step 2: Review other options

    File names can include dashes. cy.screenshot does not require chaining after cy.get(). So these are not issues.
  3. Final Answer:

    The capture option 'viewport' is valid; the problem is elsewhere. -> Option B
  4. Quick Check:

    Valid options mean issue is not in syntax [OK]
Hint: Check option values; 'viewport' is valid for capture [OK]
Common Mistakes:
  • Assuming 'viewport' is invalid
  • Thinking file names cannot have dashes
  • Believing chaining is mandatory
5. You want to take a screenshot only of a specific element with class .profile-pic and save it as 'profile.png'. Which code snippet correctly does this?
hard
A. cy.get('.profile-pic').screenshot('profile');
B. cy.screenshot('.profile-pic', { capture: 'element', fileName: 'profile.png' });
C. cy.get('.profile-pic').screenshot('profile.png.png');
D. cy.screenshot('profile.png', { element: '.profile-pic' });

Solution

  1. Step 1: Understand element screenshot syntax

    To screenshot a specific element, first select it with cy.get(), then call .screenshot() on that element. The argument is the file name without extension.
  2. Step 2: Evaluate each option

    cy.get('.profile-pic').screenshot('profile.png.png'); uses file name with extension, which is incorrect; Cypress adds extension automatically. cy.screenshot('.profile-pic', { capture: 'element', fileName: 'profile.png' }); uses invalid syntax; cy.screenshot does not accept selector as first argument. cy.get('.profile-pic').screenshot('profile'); correctly selects element and calls .screenshot('profile'). cy.screenshot('profile.png', { element: '.profile-pic' }); uses invalid options.
  3. Final Answer:

    cy.get('.profile-pic').screenshot('profile'); -> Option A
  4. Quick Check:

    Element screenshot = get element then .screenshot(name) [OK]
Hint: Select element first, then call .screenshot with name (no extension) [OK]
Common Mistakes:
  • Passing file extension in screenshot name
  • Calling cy.screenshot with selector argument
  • Using invalid options for element capture
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard