-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathunit.test.ts
More file actions
66 lines (61 loc) · 2.33 KB
/
Copy pathunit.test.ts
File metadata and controls
66 lines (61 loc) · 2.33 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
import {
createPagesEventContext,
waitOnExecutionContext,
} from "cloudflare:test";
import { describe, it } from "vitest";
import * as apiMiddleware from "../functions/api/_middleware";
import * as apiKVKeyFunction from "../functions/api/kv/[key]";
import * as apiPingFunction from "../functions/api/ping";
// This will improve in the next major version of `@cloudflare/workers-types`,
// but for now you'll need to do something like this to get a correctly-typed
// `Request` to pass to `createPagesEventContext()`.
const IncomingRequest = Request<unknown, IncomingRequestCfProperties>;
describe("functions", () => {
it("calls function", async ({ expect }) => {
const request = new IncomingRequest("http://example.com/api/ping");
const ctx = createPagesEventContext<typeof apiPingFunction.onRequest>({
request,
data: { user: "test" },
});
const response = await apiPingFunction.onRequest(ctx);
await waitOnExecutionContext(ctx);
expect(await response.text()).toBe("GET pong");
});
it("calls function with params", async ({ expect }) => {
let request = new IncomingRequest("http://example.com/api/kv/key", {
method: "PUT",
body: "value",
});
let ctx = createPagesEventContext<typeof apiKVKeyFunction.onRequestPut>({
request,
data: { user: "test" },
params: { key: "key" },
});
let response = await apiKVKeyFunction.onRequestPut(ctx);
await waitOnExecutionContext(ctx);
expect(response.status).toBe(204);
request = new IncomingRequest("http://example.com/api/kv/key");
ctx = createPagesEventContext<typeof apiKVKeyFunction.onRequestGet>({
request,
data: { user: "test" },
params: { key: "key" },
});
response = await apiKVKeyFunction.onRequestGet(ctx);
await waitOnExecutionContext(ctx);
expect(response.status).toBe(200);
expect(await response.text()).toBe("value");
});
it("calls middleware", async ({ expect }) => {
const request = new IncomingRequest("http://example.com/api/ping");
const ctx = createPagesEventContext<typeof apiMiddleware.onRequest>({
request,
async next(request) {
expect(ctx.data).toStrictEqual({ user: "ada" });
return new Response(`next:${request.method} ${request.url}`);
},
});
const response = await apiMiddleware.onRequest(ctx);
await waitOnExecutionContext(ctx);
expect(await response.text()).toBe("NEXT:GET HTTP://EXAMPLE.COM/API/PING");
});
});