Skip to content

Commit 86538fb

Browse files
committed
refactor: raise code quality based on static analyzer report
Signed-off-by: Jakub Freisler <[email protected]>
1 parent a74aa9c commit 86538fb

File tree

3 files changed

+75
-59
lines changed

3 files changed

+75
-59
lines changed

src/commands.ts

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,14 @@ declare global {
2727

2828
const nameCacheCounter: Record<string, number> = {};
2929

30+
const constructCypressError = (log: Cypress.Log, err: Error) => {
31+
// only way to throw & log the message properly in Cypress
32+
// https://github.com/cypress-io/cypress/blob/5f94cad3cb4126e0567290b957050c33e3a78e3c/packages/driver/src/cypress/error_utils.ts#L214-L216
33+
(err as unknown as { onFail: (e: Error) => void }).onFail = (err: Error) =>
34+
log.error(err);
35+
return err;
36+
};
37+
3038
Cypress.Commands.add(
3139
"matchImage",
3240
{ prevSubject: "optional" },
@@ -128,13 +136,7 @@ Cypress.Commands.add(
128136

129137
if (!res) {
130138
log.set("message", "Unexpected error!");
131-
const err = new Error("Unexpected error!");
132-
// only way to throw & log the message properly in Cypress
133-
// https://github.com/cypress-io/cypress/blob/5f94cad3cb4126e0567290b957050c33e3a78e3c/packages/driver/src/cypress/error_utils.ts#L214-L216
134-
(err as unknown as { onFail: (e: Error) => void }).onFail = (
135-
err: Error
136-
) => log.error(err);
137-
throw err;
139+
throw constructCypressError(log, new Error("Unexpected error!"));
138140
}
139141

140142
if (res.error) {
@@ -150,13 +152,7 @@ Cypress.Commands.add(
150152
)})`
151153
);
152154
log.set("consoleProps", () => res);
153-
const err = new Error(res.message);
154-
// only way to throw & log the message properly in Cypress
155-
// https://github.com/cypress-io/cypress/blob/5f94cad3cb4126e0567290b957050c33e3a78e3c/packages/driver/src/cypress/error_utils.ts#L214-L216
156-
(err as unknown as { onFail: (e: Error) => void }).onFail = (
157-
err: Error
158-
) => log.error(err);
159-
throw err;
155+
throw constructCypressError(log, new Error(res.message));
160156
} else {
161157
log.set("message", res.message);
162158
}

src/plugins.ts

Lines changed: 47 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,16 @@ import sanitize from "sanitize-filename";
99

1010
type NotFalsy<T> = T extends false | null | undefined ? never : T;
1111

12+
type CompareImagesCfg = {
13+
scaleFactor: number;
14+
title: string;
15+
imgNew: string;
16+
imgOld: string;
17+
updateImages: boolean;
18+
maxDiffThreshold: number;
19+
diffConfig: Parameters<typeof pixelmatch>[5];
20+
} & Parameters<typeof pixelmatch>[5];
21+
1222
const round = (n: number) => Math.ceil(n * 1000) / 1000;
1323

1424
const createImageResizer = (width: number, height: number) => (source: PNG) => {
@@ -17,11 +27,13 @@ const createImageResizer = (width: number, height: number) => (source: PNG) => {
1727
return resized;
1828
};
1929

30+
const inArea = (x: number, y: number, height: number, width: number) =>
31+
y > height || x > width;
32+
2033
const fillSizeDifference = (width: number, height: number) => (image: PNG) => {
21-
const inArea = (x: number, y: number) => y > height || x > width;
2234
for (let y = 0; y < image.height; y++) {
2335
for (let x = 0; x < image.width; x++) {
24-
if (inArea(x, y)) {
36+
if (inArea(x, y, height, width)) {
2537
const idx = (image.width * y + x) << 2;
2638
image.data[idx] = 0;
2739
image.data[idx + 1] = 0;
@@ -81,25 +93,22 @@ const getConfigVariableOrThrow = <K extends keyof Cypress.PluginConfigOptions>(
8193
throw `[Image snapshot] CypressConfig.${name} cannot be missing or \`false\`!`;
8294
};
8395

84-
export const initPlugin = (
85-
on: Cypress.PluginEvents,
86-
config: Cypress.PluginConfigOptions
87-
) => {
88-
if (config.env["pluginVisualRegressionForceDeviceScaleFactor"] !== false) {
89-
// based on https://github.com/cypress-io/cypress/issues/2102#issuecomment-521299946
90-
on("before:browser:launch", (browser, launchOptions) => {
91-
if (browser.name === "chrome" || browser.name === "chromium") {
92-
launchOptions.args.push("--force-device-scale-factor=1");
93-
launchOptions.args.push("--high-dpi-support=1");
94-
} else if (browser.name === "electron" && browser.isHeaded) {
95-
// eslint-disable-next-line no-console
96-
console.log(
97-
"There isn't currently a way of setting the device scale factor in Cypress when running headed electron so we disable the image regression commands."
98-
);
99-
}
100-
});
101-
}
96+
const initForceDeviceScaleFactor = (on: Cypress.PluginEvents) => {
97+
// based on https://github.com/cypress-io/cypress/issues/2102#issuecomment-521299946
98+
on("before:browser:launch", (browser, launchOptions) => {
99+
if (browser.name === "chrome" || browser.name === "chromium") {
100+
launchOptions.args.push("--force-device-scale-factor=1");
101+
launchOptions.args.push("--high-dpi-support=1");
102+
} else if (browser.name === "electron" && browser.isHeaded) {
103+
// eslint-disable-next-line no-console
104+
console.log(
105+
"There isn't currently a way of setting the device scale factor in Cypress when running headed electron so we disable the image regression commands."
106+
);
107+
}
108+
});
109+
};
102110

111+
const initTaskHooks = (on: Cypress.PluginEvents) => {
103112
on("task", {
104113
[TASK.getScreenshotPath]({ title, imagesDir, specPath }) {
105114
return path.join(
@@ -123,17 +132,7 @@ export const initPlugin = (
123132

124133
return null;
125134
},
126-
async [TASK.compareImages](
127-
cfg: {
128-
scaleFactor: number;
129-
title: string;
130-
imgNew: string;
131-
imgOld: string;
132-
updateImages: boolean;
133-
maxDiffThreshold: number;
134-
diffConfig: Parameters<typeof pixelmatch>[5];
135-
} & Parameters<typeof pixelmatch>[5]
136-
): Promise<null | {
135+
async [TASK.compareImages](cfg: CompareImagesCfg): Promise<null | {
137136
error?: boolean;
138137
message?: string;
139138
imgDiff?: number;
@@ -227,7 +226,12 @@ export const initPlugin = (
227226
return null;
228227
},
229228
});
229+
};
230230

231+
const initAfterScreenshotHook = (
232+
on: Cypress.PluginEvents,
233+
config: Cypress.PluginConfigOptions
234+
) => {
231235
on("after:screenshot", (details) => {
232236
if (details.name?.indexOf(IMAGE_SNAPSHOT_PREFIX) !== 0) return;
233237

@@ -260,3 +264,15 @@ export const initPlugin = (
260264
});
261265
});
262266
};
267+
268+
export const initPlugin = (
269+
on: Cypress.PluginEvents,
270+
config: Cypress.PluginConfigOptions
271+
) => {
272+
if (config.env["pluginVisualRegressionForceDeviceScaleFactor"] !== false) {
273+
initForceDeviceScaleFactor(on);
274+
}
275+
276+
initTaskHooks(on);
277+
initAfterScreenshotHook(on, config);
278+
};

src/support.ts

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,19 @@ function queueRun() {
1515
(cy as unknown as { queue: { run: () => void } }).queue.run();
1616
}
1717

18-
function generateOverlayTemplate(
19-
title: string,
20-
imgNewBase64: string,
21-
imgOldBase64: string,
22-
imgDiffBase64: string,
23-
wasImageNotUpdatedYet: boolean
24-
) {
25-
return `<div class="${OVERLAY_CLASS} runner" style="position:fixed;z-index:10;top:0;bottom:0;left:0;right:0;display:flex;flex-flow:column">
18+
const generateOverlayTemplate = ({
19+
title,
20+
imgNewBase64,
21+
imgOldBase64,
22+
imgDiffBase64,
23+
wasImageNotUpdatedYet,
24+
}: {
25+
title: string;
26+
imgNewBase64: string;
27+
imgOldBase64: string;
28+
imgDiffBase64: string;
29+
wasImageNotUpdatedYet: boolean;
30+
}) => `<div class="${OVERLAY_CLASS} runner" style="position:fixed;z-index:10;top:0;bottom:0;left:0;right:0;display:flex;flex-flow:column">
2631
<header style="position:static">
2732
<nav style="display:flex;width:100%;align-items:center;justify-content:space-between;padding:10px 15px;">
2833
<h2>${title} - screenshot diff</h2>
@@ -53,11 +58,10 @@ function generateOverlayTemplate(
5358
<div style="background:#fff;border:solid 15px #fff">
5459
<h3>Diff between new and old screenshot</h3>
5560
<img style="min-width:300px;width:100%" src="data:image/png;base64,${imgDiffBase64}" />
56-
</div>
5761
</div>
5862
</div>
59-
</div>`;
60-
}
63+
</div>
64+
</div>`;
6165

6266
function cachedReadFile(
6367
imageCache: Record<string, string>,
@@ -137,13 +141,13 @@ after(() => {
137141
queueClear();
138142

139143
Cypress.$(
140-
generateOverlayTemplate(
144+
generateOverlayTemplate({
141145
title,
142146
imgNewBase64,
143147
imgOldBase64,
144148
imgDiffBase64,
145-
wasImageNotUpdatedYet
146-
)
149+
wasImageNotUpdatedYet,
150+
})
147151
).appendTo(top.document.body);
148152

149153
const wrapper = Cypress.$(`.${OVERLAY_CLASS}`, top.document.body);

0 commit comments

Comments
 (0)