(#547) New matcher toHaveColor that verifies pixel colors on screen

This commit is contained in:
Simon Hofmann
2023-12-14 20:44:44 +01:00
parent 41b7b29d8c
commit 8768e804a9
2 changed files with 85 additions and 0 deletions
@@ -0,0 +1,66 @@
import { RGBA, screen } from "../../../index";
import { Point } from "../../point.class";
import { mockPartial } from "sneer";
import { toHaveColor } from "./toHaveColor.function";
// jest.mock("jimp", () => {});
const targetPoint = new Point(400, 400);
describe(".toHaveColor", () => {
it("should succeed when screen pixel has the correct RGBA value", async () => {
// GIVEN
screen.colorAt = mockPartial(() => {
return new RGBA(0, 0, 0, 0);
});
// WHEN
const result = await toHaveColor(targetPoint, new RGBA(0, 0, 0, 0));
// THEN
expect(result.pass).toBeTruthy();
});
it("should fail when the screen pixel has the incorrect RGBA value", async () => {
// GIVEN
screen.colorAt = mockPartial(() => {
return new RGBA(255, 0, 5, 0);
});
// WHEN
const result = await toHaveColor(targetPoint, new RGBA(0, 0, 0, 0));
// THEN
expect(result.pass).toBeFalsy();
});
it("should succeed when the screen pixel has the correct RGBA value", async () => {
// GIVEN
screen.colorAt = mockPartial(() => {
return new RGBA(0, 0, 0, 0);
});
expect.extend({
toHaveColor,
});
// WHEN
// THEN
await expect(targetPoint).toHaveColor(new RGBA(0, 0, 0, 0));
});
it("should succeed when the screen pixel has the incorrect RGBA value", async () => {
// GIVEN
screen.colorAt = mockPartial(() => {
return new RGBA(255, 0, 5, 0);
});
expect.extend({
toHaveColor,
});
// WHEN
// THEN
await expect(targetPoint).not.toHaveColor(new RGBA(0, 0, 0, 0));
});
});
@@ -0,0 +1,19 @@
import { Point, RGBA, screen } from "../../../index";
export const toHaveColor = async (received: Point, needle: RGBA) => {
const color = await screen.colorAt(received);
const match = color.toHex() === needle.toHex();
if (match) {
return {
message: () =>
`Expected pixel ${received.toString()} not to to have color ${needle.toHex()}`,
pass: true,
};
} else {
return {
message: () =>
`Expected pixel ${received.toString()} to have color ${needle.toHex()} but is ${color.toHex()}`,
pass: false,
};
}
};