Cypress screenshot tests

Install and configure cypress

  1. Add dependency

    1
    npm install -D cypress cypress-image-snapshot
  2. Configure plugin: create a cypress\plugins\index.js file with the following content:

    1
    2
    3
    4
    5
    6
    const { addMatchImageSnapshotPlugin } = 
    require('cypress-image-snapshot\plugin');

    module.exports = (on, config) => {
    addMatchImageSnapshotPlugin(on, config);
    };
  3. Configure support create a cypress\support\index.js file containing:

    1
    2
    3
    import { addMatchImageSnapshotCommand } from 'cypress-image-snapshot\command';

    addMatchImageSnapshotCommand();

Create the screenshot test

“Cypress visits each page of the project and it will take a screenshot of each example in the page”.

  1. Create Cypress configuration (cypress.json)

    1
    2
    3
    4
    {
    "baseUrl": "http:\\localhost:8000\",
    "video": false
    }
  2. Create the test (cypress\integration\screenshot.spec.js)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    const routes = ['badge.html', 'button.html'];

    \\ test based on the routes array
    describe('Component screenshot', () => {
    routes.forEach((route) => {
    const componentName = route.replace('.html', '');
    const testName = `${componentName} should match previous screenshot`;

    it(testName, () => {
    cy.visit(route);

    cy.get('.cypress-wrapper').each((element, index) => {
    const name = `${componentName}-${index}`;

    \\ create one image per .cypress-wrapper element that the page has
    cy.wrap(element).matchImageSnapshot(name);
    });
    });
    });
    });
  3. Create the command to trigger the tests in package.json:

    1
    2
    3
    4
    {
    "test": "cypress",
    "docker-test": "docker run -it -e CYPRESS_updateSnapshots=$CYPRESS_updateSnapshots --ipc=host -v $PWD:\e2e -w \e2e cypress\included:4.11.0"
    }
  4. Run it

    1
    2
    3
    4
    5
    6
    # run headless mode
    npm run cypress run
    # CYPRESS_updateSnapshots=true npm run docker-test

    # use Cypress runner
    npm run cypress open