-
Notifications
You must be signed in to change notification settings - Fork 2
/
testing_utils.ts
87 lines (73 loc) · 2 KB
/
testing_utils.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
// Copyright 2018-2024 the oak authors. All rights reserved.
import { createHttpError } from "@oak/commons/http_errors";
import { Status } from "@oak/commons/status";
import hyperid from "hyperid";
import type { Addr, RequestEvent } from "./types.ts";
import { createPromiseWithResolvers } from "./utils.ts";
const instance = hyperid({ urlSafe: true });
export class MockRequestEvent implements RequestEvent {
#addr: Addr;
#id = instance();
//deno-lint-ignore no-explicit-any
#reject: (reason?: any) => void;
#request: Request;
#resolve: (value: Response | PromiseLike<Response>) => void;
#responded = false;
#response: Promise<Response>;
#url: URL;
get addr(): Addr {
return this.#addr;
}
get env(): Record<string, string> {
return {};
}
get id(): string {
return this.#id;
}
get request(): Request {
return this.#request;
}
get response(): Promise<Response> {
return this.#response;
}
get responded(): boolean {
return this.#responded;
}
get url(): URL {
return this.#url;
}
constructor(
input: URL | string,
init?: RequestInit,
addr: Addr = { hostname: "localhost", port: 80, transport: "tcp" },
) {
this.#addr = addr;
this.#request = new Request(input, init);
const { promise, reject, resolve } = createPromiseWithResolvers<Response>();
this.#response = promise;
this.#reject = reject;
this.#resolve = resolve;
this.#url = URL.parse(this.#request.url) ?? new URL("http://localhost/");
}
// deno-lint-ignore no-explicit-any
error(reason?: any): void {
if (this.#responded) {
throw createHttpError(
Status.InternalServerError,
"Request already responded to.",
);
}
this.#responded = true;
this.#reject(reason);
}
respond(response: Response): void {
if (this.#responded) {
throw createHttpError(
Status.InternalServerError,
"Request already responded to.",
);
}
this.#responded = true;
this.#resolve(response);
}
}