forked from nightscout/cgm-remote-monitor
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathajax.ts
More file actions
98 lines (92 loc) · 2.22 KB
/
ajax.ts
File metadata and controls
98 lines (92 loc) · 2.22 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
import { vi } from "vitest";
export const ajaxMock = vi.fn();
export const mockState: Map<
RegExp | string,
{ data: any; error?: never } | { error: any; data?: never }
> = new Map();
type ValueOfMap<T> = T extends Map<any, infer G> ? G : never;
function mockImplementation(
opts: JQuery.AjaxSettings & { url: string }
): JQuery.jqXHR;
function mockImplementation(
maybeOpts: string,
opts?: JQuery.AjaxSettings
): JQuery.jqXHR;
function mockImplementation(
maybeOpts: (JQuery.AjaxSettings & { url: string }) | string,
opts?: JQuery.AjaxSettings
): JQuery.jqXHR {
const url = typeof maybeOpts === "string" ? maybeOpts : maybeOpts.url;
opts = typeof maybeOpts === "string" ? opts : maybeOpts;
const data = [...mockState.entries()].find(([matcher, data]) =>
url.match(matcher)
)?.[1];
if (!data) throw Error(`[mockAjax] route ${url} not handled`);
class AjaxReturnMock implements JQuery.jqXHR {
constructor(private data: ValueOfMap<typeof mockState>) {}
state() {
return "resolved" as "resolved";
}
done(callback: (d: any) => void) {
if (this.data.data) {
callback(this.data.data);
}
return this;
}
fail(callback: (d: any) => void) {
if (this.data.error) {
callback(this.data.error);
}
return this;
}
statusCode() {
return this.data.error ? 500 : 200;
}
get responseText() {
return this.data.error ? "error" : "OK";
}
abort() {}
always(callback: (d: any) => void) {
callback(this.data.data || this.data.error);
return this;
}
progress() {
return this;
}
promise() {
return this;
}
pipe() {
return this;
}
then() {
return this;
}
catch() {
return this;
}
getAllResponseHeaders() {
return "";
}
getResponseHeader() {
return "";
}
overrideMimeType() {
return "";
}
get readyState() {
return 1;
}
setRequestHeader() {
return this;
}
get status() {
return this.data.error ? 500 : 200;
}
get statusText() {
return this.data.error ? "error" : "OK";
}
}
return new AjaxReturnMock(data);
}
ajaxMock.mockImplementation(mockImplementation);