systelab-components-wdio-test
Version:
Widgets to be use in the E2E Tests based in WDIO
45 lines (44 loc) • 2.4 kB
JavaScript
import { PNG } from 'pngjs';
import * as fs from 'fs';
import Pixelmatch from 'pixelmatch';
import { ReportUtility } from "./report.util.js";
import { AssertionUtility } from "./assertion.util.js";
export class ScreenshotUtility {
static setBasePath(basePath) {
this.basePath = basePath;
}
static setPixelTolerance(pixelTolerance) {
this.pixelTolerance = pixelTolerance;
}
static setImageMatchingThreshold(imageMatchingThreshold) {
this.imageMatchingThreshold = imageMatchingThreshold;
}
static async expectPageScreenshot(page, fileName, pageDescriptiveName) {
return this.expectScreenshot(page.getElementFinder(), fileName, pageDescriptiveName);
}
static async expectWidgetScreenshot(widget, fileName, widgetDescriptiveName) {
return this.expectScreenshot(widget.getElement(), fileName, widgetDescriptiveName);
}
static async expectScreenshot(element, fileName, elementDescriptiveName) {
const actualImageFilepath = `${this.basePath}/${fileName}.actual.png`;
await element.saveScreenshot(actualImageFilepath);
const expectedImageFilepath = `${this.basePath}/${fileName}.expected.png`;
await ReportUtility.addExpectedResult(`'${elementDescriptiveName}' is equal to screenshot of '${fileName}.expected.png' file`, async () => {
const diffImageFilepath = `${this.basePath}/${fileName}.diff.png`;
const diffPixels = this.compareImageFiles(expectedImageFilepath, actualImageFilepath, diffImageFilepath);
AssertionUtility.expectLowerOrEqual(diffPixels, this.pixelTolerance);
});
}
static compareImageFiles(expectedImageFilepath, actualImageFilepath, diffImageFilepath) {
const expectedImage = PNG.sync.read(fs.readFileSync(expectedImageFilepath));
const actualImage = PNG.sync.read(fs.readFileSync(actualImageFilepath));
const { width, height } = expectedImage;
const diffImage = new PNG({ width, height });
const numDiffPixels = Pixelmatch(expectedImage.data, actualImage.data, diffImage.data, width, height, { threshold: this.imageMatchingThreshold });
fs.writeFileSync(diffImageFilepath, PNG.sync.write(diffImage));
return numDiffPixels;
}
}
ScreenshotUtility.basePath = './screenshots';
ScreenshotUtility.pixelTolerance = 0;
ScreenshotUtility.imageMatchingThreshold = 0.1;