@forsakringskassan/cypress-visual-regression

中文文档
5.2.0发布于 2026/09/05MITTypeScriptCommonJS零依赖构建来源已验证近 30 天下载 2.3万

Module for adding visual regression testing to Cypress

原始使用文档
文档目录8 节
  1. Getting Started
  2. Options
  3. To Use
  4. Implementation in test files
  5. Waiting for components to load and retry function
  6. Setting default values
  7. Saved base images and failing tests
  8. Using multiple event listeners

@forsakringskassan/cypress-visual-regression

Module for adding visual regression testing to Cypress.

This is a fork of cypress-visual-regression v1.7.0. The most notable changes are:

  • Support both headed and headless.
  • Support both E2E and Component Tests with screenshots stored next to test-cases in a __screenshots__ folder.
  • Retryability: tries multiple times to match the screenshot against the base images.
  • Delayed screenshots: optional delay before taking base screenshots.
  • Forced software rendering, antialiasing detection: to prevent flaky tests due to different hardware rendering slightly different pixels.

Getting Started

Install:

$ npm install --save-dev @forsakringskassan/cypress-visual-regression

Add the following config to your cypress.config.ts. file:

the default for screenshotsfolder is cypress/screenshots. Your screenshotfolder is where the failing tests will be transfered to.

{
    "screenshotsFolder": "WHERE_YOU_WANT_FAILING_TEST_IMAGES_TO_END_UP/",
    "trashAssetsBeforeRuns": true
}

cypress/support/commands.ts:

import "@forsakringskassan/cypress-visual-regression/commands";

cypress.config.ts:

import getToMatchScreenshotsPlugin from "@forsakringskassan/cypress-visual-regression/plugin";
import { defineConfig } from "cypress";

export default defineConfig({
    e2e: {
        setupNodeEvents(on, config) {
            config = getToMatchScreenshotsPlugin(on, config);
        },
    },
});

This plug uses the before:browser:launch event, due to Cypress#5240 if you have another plugin or you use it yourself in cypress.config.ts you need a workaround. See the section below on an example of such workaround.

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

Options

failSilently is enabled by default. Add the following config to your cypress.json file to see the errors:

{
    "env": {
        "failSilently": false
    }
}

To Use

The plugin has two modes, base and actual.

base captures a new screenshot to set as the reference image, or updates the existing one if the difference exceeds the threshold. actual captures the current screenshot and compares it against the reference image.

Default is actual.

To run in base-mode locally, add type=base as a environment variable

$ cypress run -- --env type=base

Implementation in test files

Add cy.toMatchScreenshot(); in your tests specs whenever you want to test for visual regressions. You can also add an optional error threshold: Value can range from 0.00 (no difference) to 1.00 (every pixel is different). So, if you enter an error threshold of 0.51, the test would fail only if > 51% of pixels are different.

Default value of threshold is 0.01, you can not go lower than that.

More examples:

ThresholdFails when
.25> 25%
.30> 30%
.50> 50%
.75> 75%

Sample:

it("should display the login page correctly", () => {
    cy.visit("/03.html");
    cy.get("H1").contains("Login");
    cy.toMatchScreenshot(0.1);
});

You can target a single HTML element as well:

cy.get("#my-header").toMatchScreenshot();

You can pass arguments as an object to cy.screenshot(), rather than just an error threshold, as well:

it("should display the login page correctly", () => {
    cy.visit("/03.html");
    cy.toMatchScreenshot({
        capture: "fullPage",
        errorThreshold: 0.1,
    });
});

Waiting for components to load and retry function

Sometimes things don't load for the screenshot. In order to solve this, you can use the argument baseDelay which will cy.wait(x) before taking base screenshots.

cy.toMatchScreenshot({ baseDelay: 500 });

When not running the test as base, it will retake screenshots after 200ms delay each until match or the default of 3 tries. If it doesn't find match and no more retires, test will fail. You can also configure how many retries it will make.

cy.toMatchScreenshot({ retries: 6 });

Setting default values

You can configure default values such as threshold and retries for all screenshot comparisons by adding during plugin registration.

export default defineConfig({
    e2e: {
        setupNodeEvents(on, config) {
            getToMatchScreenshotsPlugin(on, config, {
                threshold: 0.05,
                retries: 2,
            });
        },
    },
    component: {
        setupNodeEvents(on, config) {
            getToMatchScreenshotsPlugin(on, config, {
                threshold: 0.05,
                retries: 2,
            });
        },
    },
});

These defaults can be overridden in individual test calls.

Saved base images and failing tests

Base-images will be stored inside same directory in which the test is, in a sub-folder called __screenshots__. For example

root
├─┬ cypress
│ └─┬ e2e
│   ├── test.cy.ts
│   └─┬ __screenshots__
│     └── test -- should match screenshot.png
└─┬ src
  └─┬ component
    ├── component.vue
    ├── component.cy.ts
    └─┬ __screenshots__
      └── component -- should match screenshot.png

When a test fails, a sub-directory will be created under your configured screenshotsFolder, inside there will be a copy of the base image and the actual image.

Using multiple event listeners

Cypress does not support multiple listeners on the same event. This plugin uses before:browser:launch and if this collides with another plugin you can apply the following workaround:

cypress.config.ts:

/**
 * Workaround for https://github.com/cypress-io/cypress/issues/5240
 *
 * Cypress `on` cannot accept multiple listeners, since we have multiple plugins
 * trying to hook into the same eents only one of them gets called. This
 * workaround creates a wrapped `on` supporting multiple listeners.
 */
class EventForwarder {
    private emitter: EventEmitter;
    private task: Cypress.Tasks;
    public on: Cypress.PluginEvents;

    public constructor() {
        this.emitter = new EventEmitter();
        this.task = {};
        this.on = (action, arg) => {
            if (action === "task") {
                Object.assign(this.task, arg);
            } else {
                this.emitter.on(action, arg as () => void);
            }
        };
    }

    public forward(on: Cypress.PluginEvents): void {
        for (const event of this.emitter.eventNames()) {
            /* eslint-disable-next-line @typescript-eslint/no-explicit-any -- because we cannot extract the action names as a union of strings */
            on(event as any, async (...args: unknown[]) => {
                if (event === "before:browser:launch") {
                    const browser = args[0];
                    let launchOptions = args[1];
                    for (const listener of this.emitter.listeners(event)) {
                        launchOptions = await listener(browser, launchOptions);
                    }
                } else {
                    for (const listener of this.emitter.listeners(event)) {
                        await listener(...args);
                    }
                }
            });
        }
        on("task", this.task);
    }
}

export default defineConfig({
    component: {
        setupNodeEvents(cypressOn, config) {
            const eventForwarder = new EventForwarder();
            const on = eventForwarder.on;

            try {
                /* [..] */

                getToMatchScreenshotsPlugin(on, config);

                /* [..] */
            } finally {
                eventForwarder.forward(cypressOn);
            }
        },
    },
});

版本与发布记录

@forsakringskassan/cypress-visual-regression 共发布 11 个版本,首次发布于 2024/03/19;过去 12 个月发布了 6 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
5.2.0latest2026/09/052 个月前
5.1.12026/09/022 个月前
5.1.02026/08/063 个月前
5.0.02026/06/025 个月前
4.0.02026/05/255 个月前
3.1.02025/12/0311 个月前

关于 @forsakringskassan/cypress-visual-regression 的常见问题

@forsakringskassan/cypress-visual-regression 是什么?

Module for adding visual regression testing to Cypress

如何安装 @forsakringskassan/cypress-visual-regression?

在项目目录运行 npm install @forsakringskassan/cypress-visual-regression,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:cypress(^15.10.0 || ^16.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@forsakringskassan/cypress-visual-regression 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@forsakringskassan/cypress-visual-regression 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@forsakringskassan/cypress-visual-regression 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js ^22.16 || >= 24。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@forsakringskassan/cypress-visual-regression 可以商用吗?

@forsakringskassan/cypress-visual-regression 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@forsakringskassan/cypress-visual-regression 的下载量有多少?

根据 npm 官方下载统计,@forsakringskassan/cypress-visual-regression 在 2026/10/16 – 2026/11/14 这 30 天内被下载 23,498 次,日均约 783 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@forsakringskassan/cypress-visual-regression 还在维护吗?

最新版本 5.2.0 发布于 2026/09/05(2 个月前);至今共发布 11 个版本,其中过去 12 个月发布了 6 个;首次发布于 2024/03/19。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。