Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

cypress-plugin-snapshots

meinaart156.1kMIT1.4.4TypeScript support: included

Cypress snapshot functionality for data

cypress, cypress-io, cypress-plugin

readme

cypress-plugin-snapshots

Plugin for snapshot tests in Cypress.io.

NPM

Build status

cypress-plugin-snapshots

Installation

npm i cypress-plugin-snapshots -S

Usage for text snapshots

describe('data test', () => {
  it('toMatchSnapshot - JSON', () => {
    return cy.request('data.json')
      .its('body')
      .toMatchSnapshot();
  });

  it('toMatchSnapshot - JSON with options', () => {
    return cy.request('data.json')
      .its('body')
      .toMatchSnapshot({
        ignoreExtraFields: true,
      });
  });

  it('toMatchSnapshot - HTML', () => {
    cy.visit('page.html')
      .then(() => {
        cy.get('div').toMatchSnapshot();
      });
  });
});

You can pass the following options to toMatchSnapshot to override default behavior.

{
  "ignoreExtraFields": false,         // Ignore fields that are not in snapshot
  "ignoreExtraArrayItems": false,     // Ignore if there are extra array items in result
  "normalizeJson": true,              // Alphabetically sort keys in JSON
  "replace": {                        // Replace `${key}` in snapshot with `value`.
    "key": "value",
  }
}

replace Use replace with caution. Tests should be deterministic. It's often a better solution to influence your test result instead of your snapshot (by mocking data for example).

Usage for image snapshots

it('toMatchImageSnapshot - element', () => {
  cy.visit('/static/stub.html')
    .then(() => {
      cy.get('[data-test=test]')
        .toMatchImageSnapshot();
    });
});

it('toMatchImageSnapshot - whole page', () => {
  cy.visit('/static/stub.html')
    .then(() => {
      cy.document()
        .toMatchImageSnapshot();
    });
});

You can pass the following options to toMatchImageSnapshot to override default behavior.

{
  "imageConfig": {
    "createDiffImage": true,                // Should a "diff image" be created, can be disabled for performance
    "threshold": 0.01,                      // Amount in pixels or percentage before snapshot image is invalid
    "thresholdType": "percent",             // Can be either "pixel" or "percent"
  },
  "name": "custom image name",            // Naming resulting image file with a custom name rather than concatenating test titles
  "separator": "custom image separator",  // Naming resulting image file with a custom separator rather than using the default ` #`
}

You can also use any option from the cypress.screenshot arguments list.

For example:

cy.get('.element')
  .toMatchImageSnapshot({
    clip: { x: 0, y: 0, width: 100, height: 100 },
  });

Configure Cypress.io

Add this to your cypress.json configuration file:

"ignoreTestFiles": [
  "**/__snapshots__/*",
  "**/__image_snapshots__/*"
]

Plugin

Find your cypress/plugins/index.js file and change it to look like this:

const { initPlugin } = require('cypress-plugin-snapshots/plugin');

module.exports = (on, config) => {
  initPlugin(on, config);
  return config;
};

Command

Find your cypress/support/index.js file and add the following line:

import 'cypress-plugin-snapshots/commands';

Make changes to default configuration

You can customize the configuration in the cypress.json file in the root of your Cypress project.

Add the configuration below to your cypress.json file to make changes to the default values.

"env": {
  "cypress-plugin-snapshots": {
    "autoCleanUp": false,            // Automatically remove snapshots that are not used by test
    "autopassNewSnapshots": true,    // Automatically save & pass new/non-existing snapshots
    "diffLines": 3,                  // How many lines to include in the diff modal
    "excludeFields": [],             // Array of fieldnames that should be excluded from snapshot
    "ignoreExtraArrayItems": false,  // Ignore if there are extra array items in result
    "ignoreExtraFields": false,      // Ignore extra fields that are not in `snapshot`
    "normalizeJson": true,           // Alphabetically sort keys in JSON
    "prettier": true,                // Enable `prettier` for formatting HTML before comparison
    "imageConfig": {
      "createDiffImage": true,       // Should a "diff image" be created, can be disabled for performance
      "resizeDevicePixelRatio": true,// Resize image to base resolution when Cypress is running on high DPI screen, `cypress run` always runs on base resolution
      "threshold": 0.01,             // Amount in pixels or percentage before snapshot image is invalid
      "thresholdType": "percent"     // Can be either "pixels" or "percent"
    },
    "screenshotConfig": {            // See https://docs.cypress.io/api/commands/screenshot.html#Arguments
      "blackout": [],
      "capture": "fullPage",
      "clip": null,
      "disableTimersAndAnimations": true,
      "log": false,
      "scale": false,
      "timeout": 30000
    },
    "serverEnabled": true,           // Enable "update snapshot" server and button in diff modal
    "serverHost": "localhost",       // Hostname for "update snapshot server"
    "serverPort": 2121,              // Port number for  "update snapshot server"
    "updateSnapshots": false,        // Automatically update snapshots, useful if you have lots of changes
    "backgroundBlend": "difference"  // background-blend-mode for diff image, useful to switch to "overlay"
  }
}

Caveats :warning:

There is currently an issue when running "All Tests" in Cypress with this plugin. You can follow the progress on the issue here and here. When running "All Tests" any tests that utilize cypress-plugin-snapshots will throw an error.

Roadmap

Below is a list of functionality that is under consideration for implementing in a next version.

  • Fix handling of "update snapshot" button that contains a replacable field
  • Disable "update snapshots" server in headless mode
  • Add more unit tests
  • Add JSDoc documentation
  • Improve TypeScript bindings

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style.

License

This plugin is released under the MIT license.

changelog

Changelog

All notable changes to this project will be documented in this file.

This project adheres to Semantic Versioning 2.0.0.

Releases

1.4.4 - 2020-08-11

  • fixup screenshotConfig (thanks @shirotech)
  • don't start server when it is disabled (#128) (thanks @shirotech)
  • Clarify format and image options (#116) (thanks @noah-potter)
  • fixup js-base64 proper (#134) (thanks @shirotech)
  • Bump lodash from 4.17.15 to 4.17.19

1.4.0 - 2020-05-07

  • Tested plugin with Cypress 4.5.0 and upgraded dependencies
  • Add padding support to screenshots (#110) (thanks @cwmrowe)
  • Remove need for config being present in cypress.json (fixes #112)

1.3.0 - 2020-02-20

  • Added support for adding a customSeparator (#82) (thanks @erwinheitzman)
  • Bump handlebars from 4.1.2 to 4.5.3 (#86)
  • Update for cypress 4.x.x compatibility (thanks @diggabyte)
  • Update README.md (#87) (thanks @memee)

1.2.9 - 2019-08-30

  • Upgraded Cypress to 3.4.1 & other dependencies to newer versions
  • Publish the types folder (#57) (thanks @allout58)
  • Bump eslint-utils from 1.3.1 to 1.4.2 (#56) …
  • feat: Adds ability to change background-blend-mode (#53) (thanks @johnmcclumpha)

1.2.8 - 2019-08-13

  • Fix clip argument for toMatchImageSnapshot (was broken in 1.2.7)

1.2.7 - 2019-08-13

  • Update dependencies with security vulnerabilities
  • Fix imageConfig loading from cypress.json (#40) (thanks @rndmerle)
  • Update readme to reflect proper thresholdTypes (#44) (thanks @bautistaaa)
  • Added typescript definitions (thanks @basarat)
  • Adds caveat section; mentions issue #10 (thanks @sgnl)
  • Properly handle undefined path (thanks @renelux)

1.2.6 - 2019-02-25

  • fixed a bug that null values cause keepKeysFromExpected to fail (fixes #26)
  • Fix escaping of slashes (fixes #28)
  • Fixing caching of snapshot files (fixes #13)

1.2.5 - 2019-01-11

  • Breaking snapshot functionality when running all tests, previous fix breaks other functionality (Reopens #10) (Fixes #14)

1.2.4 - 2019-01-04

  • Fix broken excludedFields functionality

1.2.3 - 2018-12-30

  • Fixing snapshot filenames when running all tests (Fixes #10) (added my own Cypress.spec implementation)
  • Renamed "save server" to "server"
  • Moved code around a bit (refactoring, cleaner separation between text and image methods)
  • Upgraded Cypress to 3.1.4

1.2.2 - 2018-12-28

  • Improve jQuery detection for toMatchSnapshot

1.2.1 - 2018-12-11

  • Expose screenshot settings to toMatchImageSnapshot
  • Upgraded Cypress to 3.1.3
  • Upgraded dependencies: eslint, eslint-config-prettier, eslint-plugin-jest, prettier, socket.io and diff2html to latest version

1.2.0 - 2018-12-01

  • Add toMatchImageSnapshot functionality

1.1.6 - 2018-11-21

  • Fix serious bug in parsing old JSON format .js.snap files, was completely broken.

1.1.5 - 2018-11-20

  • Add better error logging when snapshot file contains an error
  • Run Travis tests against LTS version of node and latest version

1.1.4 - 2018-11-19

  • Read snapshot file as JSON when require throws an error (fixes handling of existing .js.snap files)

1.1.3 - 2018-11-17

  • Fixing the "Unicode Problem" present in atob/btoa by switching to js-base64 for base64 encoding/decoding. Thanks to ddfx for fixing this.
  • Reformatted the changelog

1.1.2 - 2018-11-11

  • Fixed included files property in package.json

1.1.1 - 2018-11-11

  • Added a file cache for loading the CSS & Javascript #performance
  • Removed unneeded log in the command log
  • Fixed date of release of 1.1.0 below

1.1.0 / 2018-11-11

  • IMPORTANT: Changed format of .snap files to have a nicer format for diffing HTML in git
  • Made sure config is always available (fixes #2)
  • Resolve dependency paths relative to plugin location (fixes #3)
  • Moved CSS to assets/styles.css
  • Moved javascript to assets/script.js
  • Clicking on passed snapshot now shows snapshot
  • Added support for DOM elements
  • Added prettier for formatting HTML before comparing

1.0.6 - 2018-11-07

  • Add example Cypress tests
  • Publish to npm via Travis
  • Updated vulnerable dependencies
  • Added diff to log output
  • Run Cypress on Travis
  • Upgraded Cypress peer dependency to 3.1.1

1.0.5 - 2018-10-17

  • Fix bug with null values

1.0.4 - 2018-10-16

  • Fix bug in replace functionality

1.0.3 - 2018-10-16

  • Add more documentation on options for toMatchSnapshot
  • Add replace functionality

1.0.2 - 2018-10-16

  • Add ignoreExtraArrayItems property to configuration
  • Add Travis integration
  • Add linter config
  • Add Jest unit tests

1.0.1 - 2018-10-15

  • Make ignoreExtraFields also work for (nested) arrays

1.0.0 / 2018-10-15

  • Rename minimalMatch to ignoreExtraFields

0.1.5 / 2018-10-15

  • Add minimalMatch to global configuration

0.1.4 / 2018-10-15

  • Fix bug with JSON normalization

0.1.3 / 2018-10-15

  • Add autoCleanUp to configuration
  • Add excludeFields to configuration
  • Add minimalMatch as option for toMatchSnapshot
  • Replace json-normalize dependency with own implementation

0.1.2 / 2018-10-15

  • Fix config key

0.1.1 / 2018-10-13

  • Fix path to resources in external modules

0.1.0 / 2018-10-13

  • released version 0.1.0