How to Take Screenshot in Cypress: Syntax and Examples
In Cypress, you can take a screenshot using the
cy.screenshot() command. This command captures the current state of the application under test and saves the image automatically in the screenshots folder.Syntax
The basic syntax to take a screenshot in Cypress is cy.screenshot([fileName], [options]).
fileName(optional): A string to name the screenshot file.options(optional): An object to customize the screenshot, such ascapturemode orcliparea.
If no file name is provided, Cypress generates a default name based on the test and timestamp.
javascript
cy.screenshot('homepage'); // or with options cy.screenshot('header-section', { capture: 'viewport' });
Example
This example demonstrates taking a screenshot of the homepage after visiting it. The screenshot is saved with the name homepage.
javascript
describe('Screenshot Example', () => { it('takes a screenshot of the homepage', () => { cy.visit('https://example.cypress.io'); cy.screenshot('homepage'); }); });
Output
Test passes and a screenshot named 'homepage.png' is saved in the Cypress screenshots folder.
Common Pitfalls
Common mistakes when taking screenshots in Cypress include:
- Not waiting for the page or element to load before taking the screenshot, resulting in incomplete captures.
- Using invalid file names with special characters that may cause saving errors.
- Expecting screenshots to capture elements outside the viewport without specifying options.
Always ensure the page is fully loaded and use valid file names.
javascript
/* Wrong way: Taking screenshot immediately after visit without wait */ cy.visit('https://example.cypress.io'); cy.screenshot('quick-screenshot'); /* Right way: Wait for element to be visible before screenshot */ cy.visit('https://example.cypress.io'); cy.get('header').should('be.visible'); cy.screenshot('header-visible');
Quick Reference
| Command | Description |
|---|---|
| cy.screenshot() | Takes a screenshot of the entire page or current viewport. |
| cy.screenshot('name') | Takes a screenshot and saves it with the given file name. |
| cy.screenshot({ capture: 'viewport' }) | Captures only the visible part of the page. |
| cy.screenshot({ clip: { x, y, width, height } }) | Captures a specific area of the page. |
Key Takeaways
Use cy.screenshot() to capture screenshots during Cypress tests easily.
Provide a file name to organize screenshots clearly.
Wait for elements or pages to load before taking screenshots to avoid incomplete images.
Use options like capture and clip to customize what part of the page is captured.
Avoid invalid characters in screenshot file names to prevent saving errors.