-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathvitest.setup.ts
More file actions
304 lines (268 loc) · 8.05 KB
/
Copy pathvitest.setup.ts
File metadata and controls
304 lines (268 loc) · 8.05 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import "@testing-library/jest-dom";
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();
const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
function formatDate(date: Date, pattern: string): string {
const pad = (value: number) => value.toString().padStart(2, "0");
const year = date.getUTCFullYear();
const monthIndex = date.getUTCMonth();
const day = date.getUTCDate();
const hours = date.getUTCHours();
const minutes = date.getUTCMinutes();
const seconds = date.getUTCSeconds();
return pattern
.replace("YYYY", year.toString())
.replace("MMMM", months[monthIndex])
.replace("MM", pad(monthIndex + 1))
.replace("DD", pad(day))
.replace("HH", pad(hours))
.replace("mm", pad(minutes))
.replace("ss", pad(seconds));
}
function createMoment(dateInput?: Date | string | number) {
let date =
dateInput instanceof Date
? new Date(dateInput)
: dateInput
? new Date(dateInput)
: new Date();
const api = {
format: (pattern: string = "YYYY-MM-DD") => formatDate(date, pattern),
startOf: (unit?: string) => {
if (unit === "day") {
date = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0, 0);
}
return api;
},
seconds: (seconds: number) => {
const updated = new Date(date);
updated.setSeconds(seconds);
updated.setMilliseconds(0);
date = updated;
return api;
},
};
return api;
}
(window as unknown as { moment: typeof createMoment }).moment = createMoment;
// Obsidian exposes `activeWindow`/`activeDocument` globals that resolve to the
// currently focused (possibly popped-out) window/document. In jsdom there is a
// single window, so point them at the test globals for code that prefers them
// over the bare `window`/`document` for popout-window compatibility.
if (typeof (globalThis as { activeWindow?: unknown }).activeWindow === "undefined") {
Object.defineProperty(globalThis, "activeWindow", {
configurable: true,
get: () => window,
});
}
if (typeof (globalThis as { activeDocument?: unknown }).activeDocument === "undefined") {
Object.defineProperty(globalThis, "activeDocument", {
configurable: true,
get: () => document,
});
}
if (typeof IntersectionObserver === "undefined") {
class MockIntersectionObserver implements IntersectionObserver {
constructor(
private callback: IntersectionObserverCallback,
private _options?: IntersectionObserverInit,
) {}
readonly root: Element | Document | null = null;
readonly rootMargin: string = this._options?.rootMargin ?? "0px";
readonly scrollMargin: string = this._options?.scrollMargin ?? "0px";
readonly thresholds: ReadonlyArray<number> = [0];
disconnect(): void {}
observe(target: Element): void {
this.callback(
[
{
isIntersecting: true,
target,
intersectionRatio: 1,
boundingClientRect: target.getBoundingClientRect(),
intersectionRect: target.getBoundingClientRect(),
rootBounds: null,
time: 0,
} as IntersectionObserverEntry,
],
this,
);
}
takeRecords(): IntersectionObserverEntry[] {
return [];
}
unobserve(): void {}
}
(
globalThis as unknown as { IntersectionObserver: typeof MockIntersectionObserver }
).IntersectionObserver = MockIntersectionObserver;
}
if (!Element.prototype.scrollIntoView) {
Element.prototype.scrollIntoView = () => {};
}
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;
};
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;
};
}
}
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;
};
}