Repository navigation
Expand file tree
/
Copy pathvitest.setup.ts
More file actions
50 lines (43 loc) · 1.53 KB
/
Copy pathvitest.setup.ts
File metadata and controls
50 lines (43 loc) · 1.53 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
import { afterEach } from 'vitest';
// Tests must never reach PostHog: a request that slipped past a test's own stubs would land in
// the analytics project. The SDK swallows transport errors, so blocked requests fail the test
// afterwards instead of relying on a throw surfacing. Script tags are not covered because jsdom
// does not load external scripts.
const blocked: string[] = [];
function isPosthogHost(href: string) {
try {
return /(^|\.)posthog\.com$/.test(new URL(href, 'http://localhost').hostname);
} catch {
return false;
}
}
function guard(input: unknown) {
const href = input instanceof Request ? input.url : String(input);
if (!isPosthogHost(href)) return;
blocked.push(href);
throw new Error(`Blocked PostHog request in tests: ${href}`);
}
const realFetch = globalThis.fetch;
globalThis.fetch = (input, init) => {
guard(input);
return realFetch(input, init);
};
if (typeof XMLHttpRequest !== 'undefined') {
const open = XMLHttpRequest.prototype.open as (...args: unknown[]) => void;
XMLHttpRequest.prototype.open = function (this: XMLHttpRequest, ...args: unknown[]) {
guard(args[1]);
open.apply(this, args);
};
}
if (typeof navigator !== 'undefined' && navigator.sendBeacon) {
const sendBeacon = navigator.sendBeacon.bind(navigator);
navigator.sendBeacon = (url, data) => {
guard(url);
return sendBeacon(url, data);
};
}
afterEach(() => {
if (blocked.length === 0) return;
const urls = blocked.splice(0).join(', ');
throw new Error(`Test attempted to reach PostHog: ${urls}`);
});