-
Notifications
You must be signed in to change notification settings - Fork 0
/
testlib.tsx
32 lines (27 loc) · 1.34 KB
/
testlib.tsx
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
import { createMocks } from "node-mocks-http";
import { expect } from "@jest/globals";
import { NextApiRequest, NextApiResponse } from "next";
import jwt from "jsonwebtoken";
function set_auth(req: NextApiRequest, user: string) {
const token = jwt.sign({ resource: "http://example.com", email: `${user}@example.com` }, "secret");
req.headers = { authorization: `Bearer ${token}` };
}
interface MockedApiResponse extends NextApiResponse {
_getJSONData: () => any;
}
type Handler = (req: NextApiRequest, res: NextApiResponse) => Promise<any>;
export async function post(handler: Handler, body?: any, user?: string, expected = 200) {
const { req, res }: { req: NextApiRequest; res: MockedApiResponse } = createMocks({ method: "POST" });
if (user != null) set_auth(req, user);
if (body != null) req.body = body;
await handler(req, res);
if (expected != null) expect(res.statusCode).toBe(expected);
if (expected === 200 || expected === 201) return res._getJSONData();
}
export async function get(handler: Handler, user?: string, expected = 200) {
const { req, res }: { req: NextApiRequest; res: MockedApiResponse } = createMocks({ method: "GET" });
if (user != null) set_auth(req, user);
await handler(req, res);
if (expected != null) expect(res.statusCode).toBe(expected);
if (expected === 200 || expected === 201) return res._getJSONData();
}