Skip to content

Commit a96ba1b

Browse files
committed
[IMP] test: add expect.toHaveStyle jest matcher
This commit adds a custom jest matcher `toHaveStyle` to check if a DOM element has a specific CSS style properties applied. Task: 5059476 Part-of: #7029 Signed-off-by: Lucas Lefèvre (lul) <lul@odoo.com>
1 parent bd79eea commit a96ba1b

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

tests/setup/jest_extend.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ declare global {
3939
toHaveCount(count: number): R;
4040
toHaveClass(className: string): R;
4141
toHaveAttribute(attribute: string, value: string): R;
42+
toHaveStyle(style: Record<string, string>): R;
4243
}
4344
}
4445
}
@@ -298,6 +299,29 @@ CancelledReasons: ${this.utils.printReceived(dispatchResult.reasons)}
298299
)}`;
299300
return { pass, message };
300301
},
302+
toHaveStyle(target: DOMTarget, expectedStyle: Record<string, string>) {
303+
const element = getTarget(target);
304+
if (!(element instanceof HTMLElement)) {
305+
const message = element ? "Target is not an HTML element" : "Target not found";
306+
return { pass: false, message: () => message };
307+
}
308+
const receivedStyle: Record<string, string> = {};
309+
for (const key of Object.keys(expectedStyle)) {
310+
receivedStyle[key] = element.style.getPropertyValue(key);
311+
}
312+
const pass = this.equals(receivedStyle, expectedStyle, [this.utils.iterableEquality]);
313+
const message = () =>
314+
pass
315+
? ""
316+
: `expect(target).toHaveStyle(expected);\n\n${this.utils.printDiffOrStringify(
317+
expectedStyle,
318+
receivedStyle,
319+
"Expected style",
320+
"Received style",
321+
false
322+
)}`;
323+
return { pass, message };
324+
},
301325
});
302326

303327
function getTarget(target: DOMTarget): Element | Document | Window {

0 commit comments

Comments
 (0)