forked from oakserver/oak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers_test.ts
92 lines (83 loc) · 1.98 KB
/
helpers_test.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
// Copyright 2018-2020 the oak authors. All rights reserved. MIT license.
// deno-lint-ignore-file
import { Application } from "./application.ts";
import { Context } from "./context.ts";
import { getQuery } from "./helpers.ts";
import { assertEquals } from "./test_deps.ts";
const { test } = Deno;
function createMockApp<
S extends Record<string | number | symbol, any> = Record<string, any>,
>(
state = {} as S,
): Application<S> {
return {
state,
} as any;
}
interface MockContextOptions<
S extends Record<string | number | symbol, any> = Record<string, any>,
> {
app?: Application<S>;
method?: string;
params?: Record<string, string>;
path?: string;
}
function createMockContext<
S extends Record<string | number | symbol, any> = Record<string, any>,
>(
{
app = createMockApp(),
method = "GET",
params,
path = "/",
}: MockContextOptions = {},
) {
const headers = new Headers();
return ({
app,
params,
request: {
headers: new Headers(),
method,
url: new URL(path, "https://localhost/"),
},
response: {
status: undefined,
body: undefined,
redirect(url: string | URL) {
headers.set("Location", encodeURI(String(url)));
},
headers,
},
state: app.state,
} as unknown) as Context<S>;
}
test({
name: "getQuery - basic",
fn() {
const ctx = createMockContext({ path: "/?foo=bar&bar=baz" });
assertEquals(getQuery(ctx), { foo: "bar", bar: "baz" });
},
});
test({
name: "getQuery - asMap",
fn() {
const ctx = createMockContext({ path: "/?foo=bar&bar=baz" });
assertEquals(
Array.from(getQuery(ctx, { asMap: true })),
[["foo", "bar"], ["bar", "baz"]],
);
},
});
test({
name: "getQuery - merge params",
fn() {
const ctx = createMockContext(
{ params: { foo: "qat", baz: "qat" }, path: "/?foo=bar&bar=baz" },
);
assertEquals(
getQuery(ctx, { mergeParams: true }),
{ foo: "bar", baz: "qat", bar: "baz" },
);
},
});