Repository navigation
Expand file tree
/
Copy pathvitest.setup.dom.ts
More file actions
286 lines (256 loc) · 8.23 KB
/
Copy pathvitest.setup.dom.ts
File metadata and controls
286 lines (256 loc) · 8.23 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import "@testing-library/jest-dom/vitest";
function createMemoryStorage(): Storage {
const items = new Map<string, string>();
return {
get length() {
return items.size;
},
clear: () => {
items.clear();
},
getItem: (key: string) => items.get(key) ?? null,
key: (index: number) => Array.from(items.keys())[index] ?? null,
removeItem: (key: string) => {
items.delete(key);
},
setItem: (key: string, value: string) => {
items.set(key, value);
},
};
}
function ensureLocalStorage(): void {
let storage: Storage;
try {
storage = window.localStorage;
} catch {
storage = createMemoryStorage();
}
if (!storage) {
storage = createMemoryStorage();
}
Object.defineProperty(globalThis, "localStorage", {
configurable: true,
value: storage,
});
Object.defineProperty(window, "localStorage", {
configurable: true,
value: storage,
});
}
ensureLocalStorage();
// Obsidian exposes an `activeDocument` global that resolves to the currently
// focused (possibly popped-out) document. In jsdom there is a single document,
// so point it at the test global for code that prefers it over the bare
// `document` for popout-window compatibility.
if (typeof (globalThis as { activeDocument?: unknown }).activeDocument === "undefined") {
Object.defineProperty(globalThis, "activeDocument", {
configurable: true,
get: () => document,
});
}
// Obsidian's `createFragment` builds in the main window's document.
if (typeof (globalThis as { createFragment?: unknown }).createFragment === "undefined") {
(
globalThis as {
createFragment?: (build?: (fragment: DocumentFragment) => void) => DocumentFragment;
}
).createFragment = (build) => {
const fragment = document.createDocumentFragment();
build?.(fragment);
return fragment;
};
}
// Obsidian points `activeWindow` at the focused window. Tests that open a second
// window set it as Obsidian's focus listeners would.
if (typeof (globalThis as { activeWindow?: unknown }).activeWindow === "undefined") {
(globalThis as { activeWindow?: Window }).activeWindow = window;
}
// Obsidian gives every node its window and lets an element follow a move to a
// popout. jsdom has one window and no popouts.
if (!("win" in Node.prototype)) {
Object.defineProperty(Node.prototype, "win", {
configurable: true,
get(this: Node) {
return this.ownerDocument?.defaultView ?? window;
},
});
}
if (!("doc" in Node.prototype)) {
Object.defineProperty(Node.prototype, "doc", {
configurable: true,
get(this: Node) {
return this.ownerDocument ?? document;
},
});
}
if (!("onWindowMigrated" in HTMLElement.prototype)) {
(HTMLElement.prototype as unknown as { onWindowMigrated: () => () => void }).onWindowMigrated =
() => () => {};
}
// jsdom has no layout, so nothing resizes. tests/mocks/resizeObserver.ts reports widths.
if (!("ResizeObserver" in window)) {
(window as unknown as { ResizeObserver: unknown }).ResizeObserver = class {
observe() {}
unobserve() {}
disconnect() {}
};
}
// jsdom has no `inert`. Browsers reflect it to the attribute.
if (!("inert" in HTMLElement.prototype)) {
Object.defineProperty(HTMLElement.prototype, "inert", {
configurable: true,
get(this: HTMLElement) {
return this.hasAttribute("inert");
},
set(this: HTMLElement, inert: boolean) {
this.toggleAttribute("inert", inert);
},
});
}
if (!Element.prototype.scrollIntoView) {
Element.prototype.scrollIntoView = () => {};
}
if (!(Element.prototype as unknown as { instanceOf?: unknown }).instanceOf) {
(
Element.prototype as unknown as {
instanceOf: (constructor: typeof Element) => boolean;
}
).instanceOf = function (this: Element, constructor: typeof Element): boolean {
const localConstructor = this.ownerDocument.defaultView?.[
constructor.name as keyof Window
] as unknown;
const elementConstructor =
typeof localConstructor === "function" ? localConstructor : constructor;
return this instanceof elementConstructor;
};
}
if (
!(HTMLElement.prototype as unknown as { setAttr?: (name: string, value: string) => void })
.setAttr
) {
(
HTMLElement.prototype as unknown as { setAttr: (name: string, value: string) => void }
).setAttr = function (this: HTMLElement, name: string, value: string) {
this.setAttribute(name, value);
};
}
if (!(HTMLElement.prototype as unknown as { setText?: (text: string) => void }).setText) {
(HTMLElement.prototype as unknown as { setText: (text: string) => void }).setText = function (
this: HTMLElement,
text: string,
) {
this.textContent = text;
};
}
type ObsidianDomContainer = HTMLElement | DocumentFragment;
type CreateElOptions = { text?: string; cls?: string };
function installCreateEl(proto: object): void {
const helpers = proto as {
createEl?: (tag: keyof HTMLElementTagNameMap, options?: CreateElOptions) => HTMLElement;
createDiv?: (options?: CreateElOptions) => HTMLDivElement;
createSpan?: (options?: CreateElOptions) => HTMLSpanElement;
};
if (!helpers.createEl) {
helpers.createEl = function (
this: ObsidianDomContainer,
tag: keyof HTMLElementTagNameMap,
options: CreateElOptions = {},
) {
const el = document.createElement(tag);
if (options.text !== undefined) el.textContent = options.text;
if (options.cls) el.className = options.cls;
this.appendChild(el);
return el;
};
}
if (!helpers.createDiv) {
helpers.createDiv = function (this: ObsidianDomContainer, options: CreateElOptions = {}) {
const createEl = (
this as ObsidianDomContainer & {
createEl: (
tag: keyof HTMLElementTagNameMap,
options?: CreateElOptions,
) => HTMLElement;
}
).createEl;
return createEl.call(this, "div", options) as HTMLDivElement;
};
}
if (!helpers.createSpan) {
helpers.createSpan = function (this: ObsidianDomContainer, options: CreateElOptions = {}) {
const createEl = (
this as ObsidianDomContainer & {
createEl: (
tag: keyof HTMLElementTagNameMap,
options?: CreateElOptions,
) => HTMLElement;
}
).createEl;
return createEl.call(this, "span", options) as HTMLSpanElement;
};
}
}
installCreateEl(HTMLElement.prototype);
installCreateEl(DocumentFragment.prototype);
if (!(HTMLElement.prototype as unknown as { empty?: () => void }).empty) {
(HTMLElement.prototype as unknown as { empty: () => void }).empty = function (
this: HTMLElement,
) {
while (this.firstChild) {
this.removeChild(this.firstChild);
}
};
}
// Obsidian augments HTMLElement with setCssStyles (assigns a batch of inline
// styles, the sanctioned alternative to direct `el.style.x = y` writes). jsdom
// has no such method, so mirror Obsidian's behaviour for component/DOM tests.
if (!(HTMLElement.prototype as unknown as { setCssStyles?: unknown }).setCssStyles) {
(
HTMLElement.prototype as unknown as {
setCssStyles: (styles: Partial<CSSStyleDeclaration>) => void;
}
).setCssStyles = function (this: HTMLElement, styles: Partial<CSSStyleDeclaration>) {
Object.assign(this.style, styles);
};
}
// jsdom does not implement the Web Animations API, which Svelte 5 transitions
// (e.g. transition:fade) rely on. Provide a minimal mock so components that use
// transitions can be rendered and asserted on in component tests.
//
// Known fidelity gaps (acceptable for the current suite, which only renders
// CSS fade transitions): `onfinish` fires immediately on a microtask rather
// than after the real duration, `playState` is always "finished", and
// `finished` is pre-resolved and ignores `cancel()`. If a future test needs to
// assert mid-transition or outro-timing behaviour, replace this with a fuller
// fake (e.g. a timer-driven animation) instead of relying on these defaults.
if (!Element.prototype.animate) {
(Element.prototype as unknown as { animate: () => Animation }).animate = function () {
let onfinish: (() => void) | null = null;
const animation = {
cancel() {},
finish() {},
play() {},
pause() {},
reverse() {},
currentTime: 0,
startTime: 0,
playbackRate: 1,
playState: "finished",
finished: Promise.resolve(),
effect: null,
addEventListener() {},
removeEventListener() {},
get onfinish() {
return onfinish;
},
set onfinish(fn: (() => void) | null) {
onfinish = fn;
if (fn) {
queueMicrotask(() => fn());
}
},
oncancel: null,
};
return animation as unknown as Animation;
};
}