-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathvitest.setup.ts
More file actions
69 lines (58 loc) · 2.34 KB
/
Copy pathvitest.setup.ts
File metadata and controls
69 lines (58 loc) · 2.34 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
import { beforeEach, onTestFailed, vi } from "vitest";
export const TEST_PRISMATIC_URL = "https://example.com";
vi.mock(import("./src/auth.js"), () => ({
getAccessToken: vi.fn(() => Promise.resolve("test-token")),
logout: vi.fn(() => Promise.resolve()),
createRequestParams: (data: Record<string, string | undefined>): string =>
new URLSearchParams(
Object.entries(data).filter(([, v]) => v !== undefined) as [string, string][],
).toString(),
}));
vi.mock(import("./src/context.js"), () => ({
getAuthContext: vi.fn(),
getPrismaticUrl: vi.fn(() => Promise.resolve(TEST_PRISMATIC_URL)),
hasEnvironmentCredentials: vi.fn(() =>
Boolean(process.env.PRISM_ACCESS_TOKEN || process.env.PRISM_REFRESH_TOKEN),
),
useDefaultAuthContext: vi.fn(),
useProfileAuthContext: vi.fn(),
}));
vi.mock(import("./src/utils/http.js"), () => ({
fetch: (...args: Parameters<typeof fetch>) => fetch(...args),
createFetch: () => fetch,
}));
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
const originalStderrWrite = process.stderr.write.bind(process.stderr);
const buffers = {
stdout: [] as string[],
stderr: [] as string[],
};
const chunkToString = (chunk: unknown): string => {
if (typeof chunk === "string") return chunk;
if (chunk instanceof Uint8Array) return Buffer.from(chunk).toString("utf8");
return String(chunk);
};
const interceptWrite = (buffer: string[]): ProxyHandler<typeof process.stdout.write> => ({
apply(_target, _thisArg, args: unknown[]) {
buffer.push(chunkToString(args[0]));
const callback = typeof args[1] === "function" ? args[1] : args[2];
if (typeof callback === "function") (callback as () => void)();
return true;
},
});
process.stdout.write = new Proxy(process.stdout.write, interceptWrite(buffers.stdout));
process.stderr.write = new Proxy(process.stderr.write, interceptWrite(buffers.stderr));
beforeEach(() => {
buffers.stdout.length = 0;
buffers.stderr.length = 0;
onTestFailed(() => {
if (buffers.stdout.length > 0) {
originalStdoutWrite(`\n--- captured stdout ---\n${buffers.stdout.join("")}\n`);
}
if (buffers.stderr.length > 0) {
originalStderrWrite(`\n--- captured stderr ---\n${buffers.stderr.join("")}\n`);
}
});
});
export const getStdout = (): string => buffers.stdout.join("");
export const getStderr = (): string => buffers.stderr.join("");