Giter Club home page Giter Club logo

cypress-plugin-visual-tests's Introduction

cypress-plugin-visual-tests

Plugin for snapshot tests in Cypress.io.

cypress-plugin-visual-tests is a fork of cypress-plugin-snapshots.

NPM

Build status

cypress-plugin-visual-tests

Installation

npm i cypress-plugin-visual-tests -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-visual-tests/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-visual-tests/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 โš ๏ธ

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-visual-tests 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.

cypress-plugin-visual-tests's People

Contributors

allout58 avatar appetizermonster avatar bahmutov avatar basarat avatar cwmrowe avatar dawchihliou avatar ddffx avatar dependabot[bot] avatar diggabyte avatar erwinheitzman avatar iuliancmarcu avatar johnmcclumpha avatar kiru42 avatar meinaart avatar memee avatar noah-potter avatar renovate-bot avatar renovate[bot] avatar rlux-aa avatar rndmerle avatar semantic-release-bot avatar shirotech avatar thompsonsj avatar

Stargazers

 avatar  avatar

Watchers

 avatar

cypress-plugin-visual-tests's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • fix(deps): update dependency jimp to v0.22.12
  • chore(deps): update dependency eslint-plugin-import to v2.29.1
  • chore(deps): update dependency eslint-plugin-jest to v27.9.0
  • fix(deps): update dependency express to v4.19.2
  • fix(deps): update dependency image-size to v1.1.1
  • fix(deps): update socket.io packages to v4.7.5 (socket.io, socket.io-client)
  • chore(deps): update actions/cache action to v4
  • chore(deps): update actions/checkout action to v4
  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update actions/upload-artifact action to v4
  • chore(deps): update dependency cypress to v13
  • chore(deps): update dependency eslint-config-prettier to v9
  • chore(deps): update dependency prettier to v3
  • chore(deps): update dependency rewire to v7
  • chore(deps): update github/codeql-action action to v3
  • fix(deps): update dependency fs-extra to v11
  • fix(deps): update dependency pngjs to v7
  • fix(deps): update dependency rimraf to v5
  • fix(deps): update dependency start-server-and-test to v2
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/CI.yml
  • actions/checkout v3
  • actions/setup-node v3
  • actions/cache v3
  • actions/upload-artifact v3
  • actions/checkout v3
  • actions/setup-node v3
  • actions/cache v3
.github/workflows/codeql-analysis.yml
  • actions/checkout v3
  • github/codeql-action v2
  • github/codeql-action v2
  • github/codeql-action v2
npm
cypress/package.json
  • cypress 9.7.0
  • diff2html 3.4.35
  • express 4.18.2
  • minimist 1.2.8
  • start-server-and-test 1.14.0
  • ws 8.9.0
package.json
  • diff2html 3.4.35
  • fs-extra 10.1.0
  • image-size 1.0.2
  • jimp 0.22.10
  • js-base64 3.7.2
  • lodash 4.17.21
  • pixelmatch 5.3.0
  • pngjs 6.0.0
  • rand-token 1.0.1
  • rimraf 3.0.2
  • sanitize-filename 1.6.3
  • socket.io 4.6.1
  • socket.io-client 4.6.1
  • source-map-support 0.5.21
  • unidiff 1.0.2
  • @semantic-release/changelog 6.0.3
  • @semantic-release/exec 6.0.3
  • @semantic-release/git 10.0.1
  • @semantic-release/github 8.0.7
  • eslint 8.40.0
  • eslint-config-airbnb-base 15.0.0
  • eslint-config-prettier 8.8.0
  • eslint-plugin-cypress 2.15.1
  • eslint-plugin-import 2.27.5
  • eslint-plugin-jest 27.6.0
  • jest 29.1.1
  • prettier 2.8.8
  • rewire 6.0.0
  • semantic-release 19.0.5
  • cypress 9.x
  • node >=12.22.0

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.