跳至主要内容

SnapshotAssertions

Playwright 提供了将页面和元素截图与文件中存储的预期值进行比较的方法。

expect(screenshot).toMatchSnapshot('landing-page.png');

方法

toMatchSnapshot(name)

Added in: v1.22 snapshotAssertions.toMatchSnapshot(name)
caution

要比较截图,请使用expect(page).toHaveScreenshot()代替。

确保传入的值(无论是string还是Buffer)与测试快照目录中存储的预期快照匹配。

用法

// Basic usage.
expect(await page.screenshot()).toMatchSnapshot('landing-page.png');

// Pass options to customize the snapshot comparison and have a generated name.
expect(await page.screenshot()).toMatchSnapshot('landing-page.png', {
maxDiffPixels: 27, // allow no more than 27 different pixels.
});

// Configure image matching threshold.
expect(await page.screenshot()).toMatchSnapshot('landing-page.png', { threshold: 0.3 });

// Bring some structure to your snapshot files by passing file path segments.
expect(await page.screenshot()).toMatchSnapshot(['landing', 'step2.png']);
expect(await page.screenshot()).toMatchSnapshot(['landing', 'step3.png']);

了解更多关于视觉比较的信息。

请注意,匹配快照仅适用于Playwright测试运行器。

参数

  • name string | Array<string>#

    快照名称。

  • options Object (可选)

    • maxDiffPixelRatio number (可选)#

      可接受的差异像素与总像素之比,范围在01之间。默认值可通过TestConfig.expect配置。默认情况下未设置。

    • maxDiffPixels number (可选)#

      允许存在差异的像素数量。默认值可通过TestConfig.expect配置。默认情况下未设置。

    • threshold number (optional)#

      在比较图像中相同像素之间可接受的感知色差,基于YIQ色彩空间,取值范围从零(严格)到一(宽松),默认值可通过TestConfig.expect配置。默认为0.2


toMatchSnapshot(options)

Added in: v1.22 snapshotAssertions.toMatchSnapshot(options)
caution

要比较截图,请使用expect(page).toHaveScreenshot()替代。

确保传入的值,无论是string还是Buffer,都与测试快照目录中存储的预期快照匹配。

用法

// Basic usage and the file name is derived from the test name.
expect(await page.screenshot()).toMatchSnapshot();

// Pass options to customize the snapshot comparison and have a generated name.
expect(await page.screenshot()).toMatchSnapshot({
maxDiffPixels: 27, // allow no more than 27 different pixels.
});

// Configure image matching threshold and snapshot name.
expect(await page.screenshot()).toMatchSnapshot({
name: 'landing-page.png',
threshold: 0.3,
});

了解更多关于可视化比较的信息。

请注意,匹配快照功能仅适用于Playwright测试运行器。

参数

  • options Object (optional)
    • maxDiffPixelRatio number (可选)#

      可接受的差异像素与总像素之比,范围在01之间。默认值可通过TestConfig.expect配置。默认情况下未设置。

    • maxDiffPixels number (可选)#

      允许存在差异的像素数量。默认值可通过TestConfig.expect配置。默认情况下未设置。

    • name string | Array<string> (optional)#

      快照名称。如果未传入,则在多次调用时使用测试名称和序号。

    • threshold number (optional)#

      在比较图像中相同像素之间可接受的感知色差,基于YIQ色彩空间,取值范围从零(严格)到一(宽松),默认值可通过TestConfig.expect配置。默认为0.2