Détail du package

cypress-visual-regression

Module for adding visual regression testing to Cypress

visual regression, image diff, cypress

readme

Cypress Visual Regression

npm

github actions

Plugin that adds powerful visual regression testing capabilities to Cypress:

example

Installation

npm install cypress-visual-regression

Configuration

JavaScript

Configure the visual regression plugin and environment variables in your cypress.config.js file like:

const { defineConfig } = require('cypress')
const { configureVisualRegression } = require('cypress-visual-regression')

module.exports = defineConfig({
  e2e: {
    env: {
      visualRegressionType: 'regression'
    },
    screenshotsFolder: './cypress/snapshots/actual',
    setupNodeEvents(on, config) {
      configureVisualRegression(on)
    }
  }
})

Pay attention to the visualRegressionType option. Use 'base' to generate baseline images, and 'regression' to compare current screenshot to the base screenshot

In your support file cypress/support/e2e.js add the following:

const { addCompareSnapshotCommand } = require('cypress-visual-regression/dist/command')
addCompareSnapshotCommand()

TypeScript

If you're using TypeScript, use files with a .ts extension, as follows:

cypress.config.ts

import { defineConfig } from 'cypress'
import { configureVisualRegression } from 'cypress-visual-regression'

export default defineConfig({
  e2e: {
    env: {
      visualRegressionType: 'regression'
    },
    screenshotsFolder: './cypress/snapshots/actual',
    setupNodeEvents(on, config) {
      configureVisualRegression(on)
    }
  }
})

cypress/support/e2e.ts

import { addCompareSnapshotCommand } from 'cypress-visual-regression/dist/command'
addCompareSnapshotCommand()

cypress/tsconfig.json

{
  "ts-node": {
    "transpileOnly": true,
    "compilerOptions": {
      "module": "ES2015"
    }
  }
}

For more info on how to use TypeScript with Cypress, please refer to this document.

Plugin options

All options can be configured within visualRegression prefix under env variable inside cypress.config.js file, like this:

module.exports = defineConfig({
  e2e: {
    screenshotsFolder: './cypress/snapshots/actual',
    env: {
      visualRegressionType: 'regression',
      visualRegressionBaseDirectory: 'cypress/snapshot/base',
      visualRegressionDiffDirectory: 'cypress/snapshot/diff',
      visualRegressionGenerateDiff: 'always',
      visualRegressionFailSilently: true
    }
  }
})
Variable Default Description
visualRegressionType / Either 'regression' or 'base'. Base will override any existing base images with new screenshots. Regression will compare the base to the current screenshot.
visualRegressionBaseDirectory 'cypress/snapshots/base' Path to the directory where the base snapshots will be stored.
visualRegressionDiffDirectory 'cypress/snapshots/diff' Path to the directory where the generated image differences will be stored.
visualRegressionGenerateDiff 'fail' Either 'fail', 'never' or 'always'. Determines if and when image differences are generated.
visualRegressionFailSilently false Used to decide if any error found in regression should be thrown or returned as part of the result.

To override different default arguments/options on a global level pass them to the addCompareSnapshotCommand() command:

  • cypress screenshot arguments
  • pixelmatch options
  • plugin configuration (errorThreshold, failSilently)
const { addCompareSnapshotCommand } = require('cypress-visual-regression/dist/command')
addCompareSnapshotCommand({
  capture: 'fullPage', // cypress screenshot option
  errorThreshold: 0.5, // plugin threshold option
  pixelmatchOptions: {
    threshold: 0 // pixelmatch threshold option
  }
})

How To Use

> syntax

cy.compareSnapshot(name)
cy.compareSnapshot(name, errorThreshold)
cy.compareSnapshot(name, options)

> arguments

Arguments Default Description
name / Represents the name of the base snapshot file that the actual screenshot will be compared with.
errorThreshold 0 Threshold under which any image difference will be considered as failed test. Represented in percentages.
options {} Used to provide additional cypress screenshot arguments, pixelmatch options, and failSilently and errorThreshold values.

> yields

  • .compareSnapshot() yields the Visual Regression Result object which contains the following info:
Result Type Description
error string (optional) Contains visual regression error message
images object Contains base64 string of generated images for actual, base (optional) and diff (optional) images
baseGenerated boolean (optional) Set to true if visual regression plugin was run for base generation (visualRegressionType set to 'base')
mismatchedPixels number (optional) Represents the number of total mismatched pixels during visual comparison. Set if difference were discovered
percentage number (optional) Represents the percentage of the difference between the images in decimals. Set if difference were discovered

> examples

cy.compareSnapshot('homePage') // will compare actual screenshot to current and fail if there's any difference in the images

cy.get('h1').compareSnapshot('homePage', 0.2) // will compare only the image of h1 element and fail only if the percentage of pixels that are different is bigger than 0.2 (20% difference)

cy.compareSnapshot('homePage', {errorThreshold: 1, failSilently: true}).then(comparisonResults => {
  console.log(comparisonResults.mismatchedPixels) // will print the number of mismatched pixels
  console.log(comparisonResults.percentage) // will print the percentage (in decimals) of mismatched pixels
  console.log(comparisonResults.error) // will print the visual regression error message (if any)
})

Looking for more examples? See cypress/e2e/main.cy.ts.

Tips & Tricks

Ignore some elements

Following function creates a command that allows you to hide elements of the page based on their className:

/**
 * To be called after you setup the command, in order to add a
 * hook that does stuff before the command is triggered
 */
export function beforeCompareSnapshots(
  /** Element you want to ignore */
  ignoredElementsQuerySelector: string,
  /** Main app element (if you want for the page to be loaded before triggering the command) */
  appContentQuerySelector: string = 'body'
) {
  Cypress.Commands.overwrite('compareSnapshot', (originalFn, ...args) => {
    return (
      cy
        // wait for content to be ready
        .get(appContentQuerySelector)
        // hide ignored elements
        .then(($app) => {
          return new Cypress.Promise((resolve, reject) => {
            setTimeout(() => {
              $app.find(ignoredElementsQuerySelector).css('visibility', 'hidden')
              resolve()
              // add a very small delay to wait for the elements to be there, but you should
              // make sure your test already handles this
            }, 300)
          })
        })
        .then(() => {
          return originalFn(...args)
        })
    )
  })
}

You may then use this function like:

const { addCompareSnapshotCommand } = require('cypress-visual-regression/dist/command')
const beforeCompareSnapshots = require('./commands/beforeCompareSnapshots')
addCompareSnapshotCommand({
  errorThreshold: 0.1
})
// add a before hook to compareSnapshot (this must be called AFTER compareSnapshotCommand() so the command can be overriden)
beforeCompareSnapshots(".chromatic-ignore,[data-chromatic='ignore']", '._app-content')

In this example, we ignore the elements that are also ignored by 3rd party tool Chromatic.

Debug

set process env visual_regression_log to debug to enable logging:

visual_regression_log=debug cypress open --e2e -b chrome -C cypress.base.config.ts

changelog

Change Log

v5.3.0

v5.2.3

  • Fix typo in visual regression popup

v5.2.2

v5.2.1

  • Fix bug with providing options through e2e file, fixes #267

v5.2.0

  • Enable overriding pixelmatch options, fixes #263 and #113
  • Move plugin options preparation logic to command.ts file
  • Refactor how options priority works: default < e2e file < env vars < command options
  • Update readme file describing the 'show difference' functionality

v5.1.0

  • Add a show difference functionality
  • Expose created images in the plugin results

v5.0.4

  • Fix ignored parameters from the support file, fixes #258

v5.0.3

  • Remove the unneeded sanitation in the commnads.ts file, add missing one in updateSnapshot function. Fixes #247 and #252
  • Split integration tests into platform, project and plugin tests
  • Fix a typo in documentation. Closes issue #248

v5.0.2

  • Switch to tsup library (instead of regular esbuild)
  • Remove "type": "module" from package.json file
  • Output dedicated files for cjs, esm and ts projects. Fix issues #244 and #243
  • Add tests different project setups (cjs, esm, ts)
  • Downgrade to chalk v4 (because of cjs support)

v5.0.1

  • Fixing path depth and cypress wrong saved path on headless (PR #233)
  • Fixing compareSnapshots paths (PR #233)
  • 225 v4 spec directory not included in screenshot path (PR #233)
  • Changing return type of takeScreenshot function (PR #228)
  • Restore onAfterScreenshot from the original API of 'cy screenshot' (PR #235)
  • build(deps-dev): bump vite from 4.5.2 to 4.5.3 (PR #234)

v5.0.0

  • Formatting using prettier

  • FIX: errorThreshold when used in an object

  • BREAKING: Rollback to use single keys to configure cypress-regression-plugin, instead of using an object. This is due to the fact that we cannot override an object on cypress CLI , please refer to this issue for more info .

    Now any config key will have a namespace and will follow camelCase notation:

env: {
  visualRegressionType: TypeOption
  visualRegressionBaseDirectory?: string
  visualRegressionDiffDirectory?: string
  visualRegressionGenerateDiff?: DiffOption
  visualRegressionFailSilently?: boolean
}

v4.0.0

  • Migrating to TS files
  • Adding esbuild to build plugin
  • Updating dependencies
  • Adding winston for logging
  • Adding formatting and linting

  • BREAKING: now type can be of type 'base' or 'regression'

  • BREAKING: Changed visual regression cypress envs. Now all vars related to visual regression plugin will be set inside an object like:
env: {
  visualRegression: {
    type: TypeOption
    baseDirectory?: string
    diffDirectory?: string
    generateDiff?: DiffOption
    failSilently?: boolean
  }
}

All notable changes to this project will be documented in this file. This project adheres to Semantic Versioning.

v3.0.0

  • BREAKING: Remove file name suffix (PR #172)
  • doc: update README

v2.1.1

  • fix: Prevent implicit dependency to fs in command.js (PR #161)

v2.1.0

  • feat: add environment-variable ALLOW_TO_FAIL (PR #146)

v2.0.1

  • fix: compile optional chaining (PR #145)

v2.0.0

  • Use relative spec path to compute the snapshot directory (PR #139)
  • Drop support for node v12, v15 and v17
  • Add support for node v18
  • Drop support for Cypress below v10
  • Add support for Cypress v10, v11 and v12

v1.7.0

  • Saves diff images only on failed tests (PR #110)

v1.6.3

  • TypeScript: Update docs and add type for plugin (PR #98)

v1.6.2

  • Adds missing compareSnapshot TypeScript types (PR #102)

v1.6.1

  • Uses errorThreshold from global options (PR #80)

v1.6.0

  • Fixes packaging of distribution (PR #95)

v1.5.10

  • Fixes serialize error object with socket communication (PR #94)

v1.5.9

  • Adds TypeScript support

v1.5.8

  • Bumps all dependency versions

v1.5.7

  • Bumps to Cypress v6.4.0
  • Adds errorThreshold to the global options (PR #72)

v1.5.6

  • Updates peerDependencies (PR #71)

v1.5.3

  • Bumps to Cypress v5.6.0
  • Sanitizes file names

v1.5.2

  • Bumps to Cypress v5.2.0
  • Adds ability to configure paths by environment variables

v1.5.1

  • Bumps to Cypress v5.1.0

v1.5.0

  • Bumps to Cypress v4.12.1
  • Checks if snapshot file exists before parsing it

v1.4.0

  • Bumps to Cypress v4.9.0
  • Expands canvas before image comparison so that both images fully cover each other

v1.3.0

  • Bumps to Cypress v4.5.0
  • Snapshot path now based on the CWD (process.cwd())

v1.2.0

  • Bumps to Cypress v4.3.0
  • Adds functionality to pass default arguments to compareSnapshotCommand()
  • Adds functionality to pass an object to cy.screenshot() rather than just an error threshold:

    cy.compareSnapshot('login', 0.1)
    
    // or
    
    cy.compareSnapshot('login', {
      capture: 'fullPage',
      errorThreshold: 0.1
    })
    

v1.1.0

  • Removes support for Node 8 and 9
  • Bumps to Cypress v4.2.0
  • Adds a failSilently option for ignore failures and proceeding with execution
  • Replaces mkdirp with fs.mkdir
  • Adds prepare script to run build step
  • Fixes quotes for Prettier commands in Windows

v1.0.7

  • Bumps to Cypress v4.1.0
  • Updates readme

v1.0.6

  • Bumps to Cypress v4.0.2

v1.0.5

  • Bumps to Cypress v3.6.1
  • Adds functionality for testing a single HTML element

v1.0.4

  • Bumps to Cypress v3.4.1

v1.0.3

v1.0.2

  • Bumps to Cypress v3.3.1

v1.0.1

  • Bumps to Cypress v3.2.0

v1.0.0

  • Uses pixelmatch instead of image-diff
  • BREAKING: errorThreshold now compares with the square root of the percentage of pixels that have changed. For example, if the image size is 1000 x 660, and there are 257 changed pixels, the error value would be (257 / 1000 / 660) ** 0.5 = 0.01973306715627196663293831730957.