Home  Cypress   How to take ...

How to take screenshot in cypress

Taking screenshots in Cypress is straightforward and can be done using Cypress commands. Here’s how you can take a screenshot during your test execution:

  1. Basic Screenshot: To capture a screenshot at any point during your test, use the cy.screenshot() command. By default, Cypress saves screenshots in the cypress/screenshots folder relative to your project root.

    // Take a screenshot with default options
    cy.screenshot();
    
  2. Customizing Screenshot Name: You can customize the filename and path of the screenshot using the cy.screenshot() options.

    cy.screenshot('custom-name'); // Saves as 'custom-name.png'
    
    // Specify a subfolder within the screenshots folder
    cy.screenshot('screenshots/custom-folder/custom-name');
    
  3. Capturing Only a Specific Element: If you want to capture a screenshot of a specific element on the page, you can use the .screenshot() method directly on that element.

    cy.get('.element-to-capture').screenshot();
    
  4. Conditional Screenshots: You can conditionally take screenshots based on test outcomes or specific conditions in your test logic.

    cy.get('.error-message').should('be.visible');
    cy.screenshot('error-screenshot'); // Take screenshot if error message is visible
    
  5. Taking Screenshots on Test Failures: Cypress provides a built-in way to automatically capture screenshots on test failures using plugins or Cypress' support/index.js file. This ensures that a screenshot is captured whenever a test fails.

    For example, in support/index.js:

    Cypress.on('test:after:run', (test, runnable) => {
      if (test.state === 'failed') {
        const screenshotFileName = `${runnable.parent.title} -- ${test.title} (failed).png`;
        cy.screenshot(screenshotFileName);
      }
    });
    

    This script captures a screenshot with a custom filename whenever a test fails.

  6. Screenshots in Headless Mode: Even when running Cypress in headless mode (without the GUI), you can still take screenshots, and they will be saved to the configured directory.

    // Run tests in headless mode and take a screenshot
    npx cypress run --spec "path/to/your/test.spec.js"
    

    The screenshots will be saved in cypress/screenshots relative to your project root.

Published on: Jun 28, 2024, 01:40 AM  
 

Comments

Add your comment