chai-screenshot
這個外掛程式的創建目的是使用 Chai 作為斷言庫來比較兩張圖片。
它的靈感來自 Playwright 製作的 haveScreenShot
方法和 chai-image,一個似乎沒有維護的專案。
目前僅支援 PNG 圖片。
第一步
使用 npm 安裝外掛程式
npm i chai-screenshot --save-dev
然後將其加入您的測試檔案中
const { expect, use } = require('chai');
const chaiScreenshot = require("chai-screenshot");
use(chaiScreenshot);
最後在您的測試腳本中使用它(此範例使用 mocha)
it('The screenshot should match the expected image', function() {
const actual = 'actual.png';
const expected = 'expected.png';
expect(actual).to.matchScreenshot(expected);
});
如果斷言失敗,外掛程式會建立一個名為 screenshot-output
的目錄,並在那裡產生一個差異 png 圖片。
如何使用
您可以將緩衝區、檔案路徑字串,甚至是 base64 圖片字串作為實際參數和預期參數傳遞。請隨意使用適合您的任何組合!
// Buffer:
const bufActual = Buffer.from(fs.readFileSync('actual.png'));
const bufExpected = Buffer.from(fs.readFileSync('expected.png'));
expect(bufActual).to.matchScreenshot(bufExpected);
// Filepath
expect('assets/actual.png').to.matchScreenshot('assets/expected.png');
// Base64 (example uses Selenium):
const actual = await driver.findElement({id: 'canvas'}).takeScreenshot(true);
expect(actual).to.matchScreenshot('assets/expected.png');
這個外掛程式在底層使用 pixelmatch 進行視覺比較。因此,這也表示您可以設定 pixelmatch 進行差異比較時所需的選項。在這個範例中,讓我們將 threshold 選項設定為較不敏感
expect("actual.png").to.matchScreenshot('expected.png', {
diff: { threshold: 0.5 }
});
您可以在這裡查看完整的 pixelmatch 選項列表。
如果您想設定不同的目錄來儲存測試失敗後的輸出(圖片差異),或重新命名預設的檔案名稱,您可以這樣設定選項
expect("actual.png").to.matchScreenshot('expected.png', {
diff: { threshold: 0.5 },
output: {
dir: 'myFolder',
name: 'test.png'} // Don't forget to add the .png extension
});
貢獻
想要貢獻嗎?您是否看到可以修正的錯字或糟糕的程式碼?
✨歡迎您的 PR!✨
您也可以建立問題並討論可以進行哪些改進。