forked from coder/coder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjest.setup.ts
More file actions
80 lines (71 loc) · 2.41 KB
/
Copy pathjest.setup.ts
File metadata and controls
80 lines (71 loc) · 2.41 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
import "@testing-library/jest-dom";
import { cleanup } from "@testing-library/react";
import crypto from "crypto";
import { server } from "testHelpers/server";
import "jest-location-mock";
import { TextEncoder, TextDecoder } from "util";
import { Blob } from "buffer";
import jestFetchMock from "jest-fetch-mock";
import { ProxyLatencyReport } from "contexts/useProxyLatency";
import { Region } from "api/typesGenerated";
import { useMemo } from "react";
jestFetchMock.enableMocks();
// useProxyLatency does some http requests to determine latency.
// This would fail unit testing, or at least make it very slow with
// actual network requests. So just globally mock this hook.
jest.mock("contexts/useProxyLatency", () => ({
useProxyLatency: (proxies?: Region[]) => {
// Must use `useMemo` here to avoid infinite loop.
// Mocking the hook with a hook.
const proxyLatencies = useMemo(() => {
if (!proxies) {
return {} as Record<string, ProxyLatencyReport>;
}
return proxies.reduce(
(acc, proxy) => {
acc[proxy.id] = {
accurate: true,
// Return a constant latency of 8ms.
// If you make this random it could break stories.
latencyMS: 8,
at: new Date(),
};
return acc;
},
{} as Record<string, ProxyLatencyReport>,
);
}, [proxies]);
return { proxyLatencies, refetch: jest.fn() };
},
}));
global.TextEncoder = TextEncoder;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Polyfill for jsdom
global.TextDecoder = TextDecoder as any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Polyfill for jsdom
global.Blob = Blob as any;
global.scrollTo = jest.fn();
// Polyfill the getRandomValues that is used on utils/random.ts
Object.defineProperty(global.self, "crypto", {
value: {
getRandomValues: function (buffer: Buffer) {
return crypto.randomFillSync(buffer);
},
},
});
// Establish API mocking before all tests through MSW.
beforeAll(() =>
server.listen({
onUnhandledRequest: "warn",
}),
);
// Reset any request handlers that we may add during the tests,
// so they don't affect other tests.
afterEach(() => {
cleanup();
server.resetHandlers();
jest.clearAllMocks();
});
// Clean up after the tests are finished.
afterAll(() => server.close());
// This is needed because we are compiling under `--isolatedModules`
export {};