Skip to content

Commit

Permalink
Support different sizes of actual and expected
Browse files Browse the repository at this point in the history
With this support playwright can show actual, expected and diff. So it's easier to see what's wrong.
  • Loading branch information
pmatter committed Aug 13, 2024
1 parent 55b5bc4 commit 44b629d
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions server/src/compare.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,21 @@ import pixelmatch from "pixelmatch";
import { PNG } from "pngjs";

export async function compare(expected, actual, options = { threshold: 0.01 }) {
const { width, height, data: expectedPng } = PNG.sync.read(expected);
const { data: actualPng } = PNG.sync.read(actual);
const diffPng = new PNG({ width, height });
const expectedPng = PNG.sync.read(expected);
const actualPng = PNG.sync.read(actual);
const diffDimensions = {
width: Math.max(expectedPng.width, actualPng.width),
height: Math.max(expectedPng.height, actualPng.height),
};
const resizedExpectedPng = createResized(expectedPng, diffDimensions);
const resizedActualPng = createResized(actualPng, diffDimensions);
const diffPng = new PNG(diffDimensions);
const numDiffPixels = pixelmatch(
expectedPng,
actualPng,
resizedExpectedPng.data,
resizedActualPng.data,
diffPng.data,
width,
height,
diffDimensions.width,
diffDimensions.height,
options,
);
const diff = PNG.sync.write(diffPng);
Expand All @@ -22,3 +28,20 @@ export async function compare(expected, actual, options = { threshold: 0.01 }) {
diff,
};
}

/** Cretes a copy of {@link img}, with the {@link dimensions}.
* @param {PNG} img
* @param {{width: number, height: number}} dimensions
* @returns {PNG}
*/
function createResized(img, dimensions) {
if (img.width > dimensions.width || img.height > dimensions.height) {
throw new Error(
`New dimensions expected to be greater than or equal to the original dimensions!`,
);
}
const resized = new PNG(dimensions);
PNG.bitblt(img, resized, 0, 0, img.width, img.height);

return resized;
}

0 comments on commit 44b629d

Please sign in to comment.