forked from ariakit/ariakit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vitest.setup.ts
83 lines (76 loc) · 2.55 KB
/
vitest.setup.ts
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
71
72
73
74
75
76
77
78
79
80
81
82
83
import { Suspense, createElement, version } from "react";
import { render } from "@ariakit/test";
import type { TestingLibraryMatchers } from "@testing-library/jest-dom/matchers.js";
import _matchers from "@testing-library/jest-dom/matchers.js";
import failOnConsole from "vitest-fail-on-console";
const matchers = _matchers as unknown as typeof _matchers.default;
declare module "vitest" {
interface JestAssertion<T = any>
extends jest.Matchers<void, T>,
TestingLibraryMatchers<T, void> {}
}
failOnConsole();
expect.extend(matchers);
expect.extend({
toHaveFocus(element: HTMLElement, expected, options) {
const toHaveFocus = matchers.toHaveFocus.bind(this) as any;
const result = toHaveFocus(element, expected, options);
const { activeElement } = element.ownerDocument;
const activeId =
activeElement && activeElement.getAttribute("aria-activedescendant");
return {
...result,
pass: result.pass || activeId === element.id,
message: () => {
if (activeId) {
return [
this.utils.matcherHint(
`${this.isNot ? ".not" : ""}.toHaveFocus`,
"element",
"",
),
"",
"Expected:",
` ${this.utils.printExpected(element)}`,
"Received:",
` ${this.utils.printReceived(
element.ownerDocument.getElementById(activeId),
)}`,
].join("\n");
}
return result.message();
},
};
},
});
if (version.startsWith("17")) {
vi.mock("react", async () => {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const actual = await vi.importActual<typeof import("react")>("react");
const mocks = {
useDeferredValue: <T>(v: T) => v,
useTransition: () => [false, (v: () => any) => v()],
useId: () => {
const [id, setId] = actual.useState<string | undefined>();
actual.useLayoutEffect(() => {
const random = Math.random().toString(36).substr(2, 6);
setId(`id-${random}`);
}, []);
return id;
},
};
return { ...mocks, ...actual };
});
}
beforeEach(async ({ meta }) => {
const filename = meta.file?.name;
if (!filename) return;
const match = filename.match(/examples\/(.*)\/test.ts$/);
if (!match) return;
const [, example] = match;
const { default: comp } = await import(`./examples/${example}/index.tsx`);
const { unmount } = render(
createElement(Suspense, { fallback: null, children: createElement(comp) }),
);
return unmount;
});