跳到主要內容

SnapshotAssertions

Playwright 提供了比較頁面和元素螢幕截圖與儲存在檔案中預期值的方法。

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

方法

toMatchSnapshot(name)

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

若要比較螢幕截圖,請改用 expect(page).toHaveScreenshot()

確保傳入的值(字串或 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 字串 | 陣列<字串>#

    快照名稱。

  • options 物件 (選填)

    • maxDiffPixelRatio 數字 (選填)#

      可接受的不同像素比例,介於 01 之間。預設值可透過 TestConfig.expect 設定。預設為未設定。

    • maxDiffPixels 數字 (選填)#

      可接受的不同像素數量。預設值可透過 TestConfig.expect 設定。預設為未設定。

    • threshold 數字 (選填)#

      可接受的感知色彩差異,在比較影像中相同像素之間的 YIQ 色彩空間中,介於零(嚴格)和一(寬鬆)之間,預設值可透過 TestConfig.expect 設定。預設值為 0.2


toMatchSnapshot(options)

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

若要比較螢幕截圖,請改用 expect(page).toHaveScreenshot()

確保傳入的值(字串或 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 物件 (選填)
    • maxDiffPixelRatio 數字 (選填)#

      可接受的不同像素比例,介於 01 之間。預設值可透過 TestConfig.expect 設定。預設為未設定。

    • maxDiffPixels 數字 (選填)#

      可接受的不同像素數量。預設值可透過 TestConfig.expect 設定。預設為未設定。

    • name 字串 | 陣列<字串> (選填)#

      快照名稱。若未傳入,多次呼叫時將使用測試名稱和序號。

    • threshold 數字 (選填)#

      可接受的感知色彩差異,在比較影像中相同像素之間的 YIQ 色彩空間中,介於零(嚴格)和一(寬鬆)之間,預設值可透過 TestConfig.expect 設定。預設值為 0.2