npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@kiru42/cypress-plugin-visual-tests

v1.5.37

Published

Cypress snapshot functionality for data

Downloads

448

Readme

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 :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-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.