-
Notifications
You must be signed in to change notification settings - Fork 233
/
testing.ts
194 lines (182 loc) · 4.89 KB
/
testing.ts
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
// Copyright 2018-2024 the oak authors. All rights reserved. MIT license.
// deno-lint-ignore-file no-explicit-any
/**
* A collection of utility APIs which can make testing of an oak application
* easier.
*
* @module
*/
import type { Application, State } from "./application.ts";
import {
accepts,
createHttpError,
type ErrorStatus,
SecureCookieMap,
} from "./deps.ts";
import { Body } from "./body.ts";
import type { RouteParams, RouterContext } from "./router.ts";
import type { Request } from "./request.ts";
import { Response } from "./response.ts";
/** Creates a mock of `Application`. */
export function createMockApp<
S extends Record<PropertyKey, any> = Record<string, any>,
>(
state: S = {} as S,
): Application<S> {
const app = {
state,
use() {
return app;
},
[Symbol.for("Deno.customInspect")]() {
return "MockApplication {}";
},
[Symbol.for("nodejs.util.inspect.custom")](
depth: number,
options: any,
inspect: (value: unknown, options?: unknown) => string,
) {
if (depth < 0) {
return options.stylize(`[MockApplication]`, "special");
}
const newOptions = Object.assign({}, options, {
depth: options.depth === null ? null : options.depth - 1,
});
return `${options.stylize("MockApplication", "special")} ${
inspect({}, newOptions)
}`;
},
} as any;
return app;
}
/** Options that can be set in a mock context. */
export interface MockContextOptions<
R extends string,
P extends RouteParams<R> = RouteParams<R>,
S extends State = Record<string, any>,
> {
app?: Application<S>;
ip?: string;
method?: string;
params?: P;
path?: string;
state?: S;
headers?: [string, string][];
body?: ReadableStream;
}
/** Allows external parties to modify the context state. */
export const mockContextState = {
/** Adjusts the return value of the `acceptedEncodings` in the context's
* `request` object. */
encodingsAccepted: "identity",
};
/** Create a mock of `Context` or `RouterContext`. */
export function createMockContext<
R extends string,
P extends RouteParams<R> = RouteParams<R>,
S extends State = Record<string, any>,
>(
{
ip = "127.0.0.1",
method = "GET",
params,
path = "/",
state,
app = createMockApp(state),
headers: requestHeaders,
body = undefined,
}: MockContextOptions<R> = {},
): RouterContext<R, P, S> {
function createMockRequest(): Request {
const headers = new Headers(requestHeaders);
return {
get source(): globalThis.Request | undefined {
return new globalThis.Request(new URL(path, "http://localhost/"), {
method,
headers,
});
},
accepts(...types: string[]) {
if (!headers.has("Accept")) {
return;
}
if (types.length) {
return accepts({ headers }, ...types);
}
return accepts({ headers });
},
acceptsEncodings() {
return mockContextState.encodingsAccepted;
},
headers,
ip,
method,
path,
search: undefined,
searchParams: new URLSearchParams(),
url: new URL(path, "http://localhost/"),
hasBody: !!body,
body: body ? new Body({ headers, getBody: () => body }) : undefined,
} as any;
}
const request = createMockRequest();
const response = new Response(request);
const cookies = new SecureCookieMap(request, { response });
return ({
app,
params,
request,
cookies,
response,
state: Object.assign({}, app.state),
assert(
condition: any,
errorStatus: ErrorStatus = 500,
message?: string,
props?: Record<string, unknown>,
): asserts condition {
if (condition) {
return;
}
const err = createHttpError(errorStatus, message);
if (props) {
Object.assign(err, props);
}
throw err;
},
throw(
errorStatus: ErrorStatus,
message?: string,
props?: Record<string, unknown>,
): never {
const err = createHttpError(errorStatus, message);
if (props) {
Object.assign(err, props);
}
throw err;
},
[Symbol.for("Deno.customInspect")]() {
return `MockContext {}`;
},
[Symbol.for("nodejs.util.inspect.custom")](
depth: number,
options: any,
inspect: (value: unknown, options?: unknown) => string,
) {
if (depth < 0) {
return options.stylize(`[MockContext]`, "special");
}
const newOptions = Object.assign({}, options, {
depth: options.depth === null ? null : options.depth - 1,
});
return `${options.stylize("MockContext", "special")} ${
inspect({}, newOptions)
}`;
},
} as unknown) as RouterContext<R, P, S>;
}
/** Creates a mock `next()` function which can be used when calling
* middleware. */
export function createMockNext(): () => Promise<void> {
return async function next() {};
}