-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathvitest.setup.ts
More file actions
70 lines (64 loc) · 2.24 KB
/
Copy pathvitest.setup.ts
File metadata and controls
70 lines (64 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { expect } from "vitest";
/**
* Get the currently focused element, traversing shadow DOM boundaries.
*/
function getActiveElement(root: Document | ShadowRoot = document) {
if (
root.activeElement &&
"shadowRoot" in root.activeElement &&
root.activeElement.shadowRoot
) {
return getActiveElement(root.activeElement.shadowRoot);
}
return root.activeElement;
}
/**
* Custom Vitest matchers for calendar component testing.
*/
expect.extend({
/**
* Custom matcher for CSS Parts API (Shadow Parts).
* Checks if an element's part attribute contains the specified value.
*/
toHavePart(element: Element, expectedPart: string) {
const { isNot } = this;
const hasPart = element.part?.contains(expectedPart) ?? false;
return {
pass: hasPart,
message: () => {
const parts = element.part
? Array.from(element.part).join(", ")
: "none";
if (isNot) {
return `Expected element not to have part "${expectedPart}", but it does.\nElement parts: ${parts}`;
}
return `Expected element to have part "${expectedPart}", but it doesn't.\nElement parts: ${parts}`;
},
};
},
/**
* Custom matcher for checking active element with Shadow DOM support.
*
* Note: Vitest's built-in toHaveFocus() doesn't work properly with Shadow DOM -
* it times out even with retry logic because it can't traverse shadow boundaries
* to find the actually focused element.
*
* This matcher uses getActiveElement() to recursively find the focused element
* within shadow trees, while still providing Vitest's retry-ability through the
* custom matcher infrastructure.
*/
toBeActiveElement(element: Element, root?: Document | ShadowRoot) {
const { isNot } = this;
const activeElement = getActiveElement(root);
const isFocused = activeElement === element;
return {
pass: isFocused,
message: () => {
if (isNot) {
return `Expected element not to be the active element, but it is.`;
}
return `Expected element to be the active element, but it isn't.\nActive element: ${activeElement?.tagName || "null"}`;
},
};
},
});