Skip to content

feat: show comparison for successful tests #137

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 23 additions & 20 deletions src/commands.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { FILE_SUFFIX, LINK_PREFIX, TASK } from "./constants";
import type pixelmatch from "pixelmatch";
import * as Base64 from "@frsource/base64";
import type { CompareImagesTaskReturn } from "./types";

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
Expand Down Expand Up @@ -116,7 +117,7 @@ Cypress.Commands.add(
})
.then((imgPath) =>
cy
.task(
.task<CompareImagesTaskReturn>(
TASK.compareImages,
{
scaleFactor,
Expand All @@ -129,12 +130,7 @@ Cypress.Commands.add(
{ log: false }
)
.then((res) => ({
res: res as null | {
error?: boolean;
message?: string;
imgDiff?: number;
maxDiffThreshold?: number;
},
res,
imgPath,
}))
)
Expand All @@ -150,22 +146,29 @@ Cypress.Commands.add(
throw constructCypressError(log, new Error("Unexpected error!"));
}

log.set(
"message",
`${res.message}${
res.imgDiffBase64 && res.imgNewBase64 && res.imgOldBase64
? `\n[See comparison](${LINK_PREFIX}${Base64.encode(
encodeURIComponent(
JSON.stringify({
title,
imgPath,
imgDiffBase64: res.imgDiffBase64,
imgNewBase64: res.imgNewBase64,
imgOldBase64: res.imgOldBase64,
error: res.error
})
)
)})`
: ''
}`
);

if (res.error) {
log.set(
"message",
`${res.message}\n[See comparison](${LINK_PREFIX}${Base64.encode(
encodeURIComponent(
JSON.stringify({
title,
imgPath,
})
)
)})`
);
log.set("consoleProps", () => res);
throw constructCypressError(log, new Error(res.message));
} else {
log.set("message", res.message);
}
});
}
Expand Down
61 changes: 9 additions & 52 deletions src/support.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,23 @@ export const generateOverlayTemplate = ({
imgOldBase64,
imgDiffBase64,
wasImageNotUpdatedYet,
error,
}: {
title: string;
imgNewBase64: string;
imgOldBase64: string;
imgDiffBase64: string;
wasImageNotUpdatedYet: boolean;
error: boolean
}) => `<div class="${OVERLAY_CLASS} runner" style="position:fixed;z-index:10;top:0;bottom:0;left:0;right:0;display:flex;flex-flow:column">
<header style="position:static">
<nav style="display:flex;width:100%;align-items:center;justify-content:space-between;padding:10px 15px;">
<h2>${title} - screenshot diff</h2>
<form>
<form style="display:flex;align-items:center;gap:5px;text-align:right">
${
wasImageNotUpdatedYet
? `<button type="submit"><i class="fa fa-check"></i> Update screenshot</button>`
: "Image was already updated, rerun test to see new comparison"
: error ? "Image was already updated, rerun test to see new comparison" : ""
}
<button type="button" data-type="close"><i class="fa fa-times"></i> Close</button>
<form>
Expand Down Expand Up @@ -64,30 +66,13 @@ export const generateOverlayTemplate = ({
</div>
</div>`;

export function cachedReadFile(
imageCache: Record<string, string>,
path: string,
encoding: Cypress.Encodings
): Cypress.Chainable<string> {
if (imageCache[path])
return Cypress.Promise.resolve(
imageCache[path]
) as unknown as Cypress.Chainable<string>;

return cy
.readFile(path, encoding, { log: false })
.then((file) => (imageCache[path] = file));
}

/* c8 ignore start */
before(() => {
if (!top) return null;
Cypress.$(`.${OVERLAY_CLASS}`, top.document.body).remove();
});

after(() => {
const imageCache: Record<string, string> = {};

if (!top) return null;

Cypress.$(top.document.body).on(
Expand All @@ -97,7 +82,7 @@ after(() => {
e.preventDefault();
if (!top) return false;

const { title, imgPath } = JSON.parse(
const { title, imgPath, imgDiffBase64, imgNewBase64, imgOldBase64, error } = JSON.parse(
decodeURIComponent(
Base64.decode(
e.currentTarget.getAttribute("href").substring(LINK_PREFIX.length)
Expand All @@ -106,39 +91,10 @@ after(() => {
);
queueClear();

cachedReadFile(imageCache, imgPath, "base64")
.then((imgNew) =>
cachedReadFile(
imageCache,
imgPath.replace(FILE_SUFFIX.actual, ""),
"base64"
).then((imgOld) =>
cachedReadFile(
imageCache,
imgPath.replace(FILE_SUFFIX.actual, FILE_SUFFIX.diff),
"base64"
).then((imgDiff) =>
cy
.task(TASK.doesFileExist, { path: imgPath }, { log: false })
.then(
(wasImageNotUpdatedYet) =>
[
imgNew,
imgOld,
imgDiff,
wasImageNotUpdatedYet as boolean,
] as const
)
)
)
)
cy
.task<boolean>(TASK.doesFileExist, { path: imgPath }, { log: false })
.then(
([
imgNewBase64,
imgOldBase64,
imgDiffBase64,
wasImageNotUpdatedYet,
]) => {
(wasImageNotUpdatedYet) => {
if (!top) return false;
queueClear();

Expand All @@ -148,6 +104,7 @@ after(() => {
imgNewBase64,
imgOldBase64,
imgDiffBase64,
error,
wasImageNotUpdatedYet,
})
).appendTo(top.document.body);
Expand Down
25 changes: 18 additions & 7 deletions src/task.hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import moveFile from "move-file";
import sanitize from "sanitize-filename";
import { FILE_SUFFIX, IMAGE_SNAPSHOT_PREFIX, TASK } from "./constants";
import { alignImagesToSameSize, importAndScaleImage } from "./image.utils";
import type { CompareImagesTaskReturn } from "./types";

export type CompareImagesCfg = {
scaleFactor: number;
Expand Down Expand Up @@ -54,14 +55,10 @@ export const approveImageTask = ({ img }: { img: string }) => {

export const compareImagesTask = async (
cfg: CompareImagesCfg
): Promise<null | {
error?: boolean;
message?: string;
imgDiff?: number;
maxDiffThreshold?: number;
}> => {
): Promise<CompareImagesTaskReturn> => {
const messages = [] as string[];
let imgDiff: number | undefined;
let imgNewBase64: string, imgOldBase64: string, imgDiffBase64: string;
let error = false;

if (fs.existsSync(cfg.imgOld) && !cfg.updateImages) {
Expand Down Expand Up @@ -107,15 +104,23 @@ export const compareImagesTask = async (
error = true;
}

const diffBuffer = PNG.sync.write(diff);
imgNewBase64 = PNG.sync.write(imgNew).toString('base64');
imgDiffBase64 = diffBuffer.toString('base64');
imgOldBase64 = PNG.sync.write(imgOld).toString('base64');

if (error) {
fs.writeFileSync(
cfg.imgNew.replace(FILE_SUFFIX.actual, FILE_SUFFIX.diff),
PNG.sync.write(diff)
diffBuffer
);
return {
error,
message: messages.join("\n"),
imgDiff,
imgNewBase64,
imgDiffBase64,
imgOldBase64,
maxDiffThreshold: cfg.maxDiffThreshold,
};
} else {
Expand All @@ -125,6 +130,9 @@ export const compareImagesTask = async (
} else {
// there is no "old screenshot" or screenshots should be immediately updated
imgDiff = 0;
imgNewBase64 = '';
imgDiffBase64 = '';
imgOldBase64 = '';
moveFile.sync(cfg.imgNew, cfg.imgOld);
}

Expand All @@ -139,6 +147,9 @@ export const compareImagesTask = async (
return {
message: messages.join("\n"),
imgDiff,
imgNewBase64,
imgDiffBase64,
imgOldBase64,
maxDiffThreshold: cfg.maxDiffThreshold,
};
}
Expand Down
9 changes: 9 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export type CompareImagesTaskReturn = null | {
error?: boolean;
message?: string;
imgDiff?: number;
imgNewBase64?: string;
imgDiffBase64?: string;
imgOldBase64?: string;
maxDiffThreshold?: number;
};