跳到主要内容

SnapshotAssertions

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

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

方法

toMatchSnapshot(name)

新增于: v1.22 snapshotAssertions.toMatchSnapshot(name)
注意

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

确保传递的值,可以是 stringBuffer,与存储在测试快照目录中的预期快照匹配。

用法

// 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 (可选)#

      YIQ 色彩空间中,相同像素在比较图像之间的可接受的感知颜色差异,介于零(严格)和一(宽松)之间,默认值可通过 TestConfig.expect 进行配置。默认为 0.2


toMatchSnapshot(options)

新增于: v1.22 snapshotAssertions.toMatchSnapshot(options)
注意

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

确保传递的值,可以是 stringBuffer,与存储在测试快照目录中的预期快照匹配。

用法

// 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 (可选)
    • maxDiffPixelRatio number (可选)#

      可接受的与总像素量不同的像素比率,介于 01 之间。默认值可通过 TestConfig.expect 进行配置。默认情况下未设置。

    • maxDiffPixels number (可选)#

      可接受的不同像素数量。默认值可通过 TestConfig.expect 进行配置。默认情况下未设置。

    • name string | Array<string> (可选)#

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

    • threshold number (可选)#

      YIQ 色彩空间中,相同像素在比较图像之间的可接受的感知颜色差异,介于零(严格)和一(宽松)之间,默认值可通过 TestConfig.expect 进行配置。默认为 0.2