1 | import {URL} from 'url';
|
2 | import httpMocks, {RequestMethod} from 'node-mocks-http';
|
3 | import stream from 'stream';
|
4 | import Koa, {Context} from 'koa';
|
5 |
|
6 | import createMockCookies, {MockCookies} from '../create-mock-cookies';
|
7 |
|
8 | export interface Dictionary<T> {
|
9 | [key: string]: T;
|
10 | }
|
11 |
|
12 | export interface MockContext extends Context {
|
13 | cookies: MockCookies;
|
14 | request: Context['Request'] & {
|
15 | body?: any;
|
16 | session?: any;
|
17 | };
|
18 | }
|
19 |
|
20 | export interface Options<
|
21 | CustomProperties extends Object,
|
22 | RequestBody = undefined
|
23 | > {
|
24 | url?: string;
|
25 | method?: RequestMethod;
|
26 | statusCode?: number;
|
27 | session?: Dictionary<any>;
|
28 | headers?: Dictionary<string>;
|
29 | cookies?: Dictionary<string>;
|
30 | state?: Dictionary<any>;
|
31 | encrypted?: boolean;
|
32 | host?: string;
|
33 | requestBody?: RequestBody;
|
34 | throw?: Function;
|
35 | redirect?: Function;
|
36 | customProperties?: CustomProperties;
|
37 | }
|
38 |
|
39 | export default function createContext<
|
40 | CustomProperties,
|
41 | RequestBody = undefined
|
42 | >(
|
43 | options: Options<CustomProperties, RequestBody> = {},
|
44 | ): MockContext & CustomProperties {
|
45 | const app = new Koa();
|
46 |
|
47 | const {
|
48 | cookies,
|
49 | method,
|
50 | statusCode,
|
51 | session,
|
52 | requestBody,
|
53 | url = '',
|
54 | host = 'test.com',
|
55 | encrypted = false,
|
56 | throw: throwFn = jest.fn(),
|
57 | redirect = jest.fn(),
|
58 | headers = {},
|
59 | state = {},
|
60 | customProperties = {},
|
61 | } = options;
|
62 |
|
63 | const extensions = {
|
64 | ...customProperties,
|
65 | throw: throwFn,
|
66 | session,
|
67 | redirect,
|
68 | state,
|
69 | };
|
70 |
|
71 | Object.assign(app.context, extensions);
|
72 |
|
73 | const protocolFallback = encrypted ? 'https' : 'http';
|
74 | const urlObject = new URL(url, `${protocolFallback}://${host}`);
|
75 |
|
76 | const req = httpMocks.createRequest({
|
77 | url: urlObject.toString(),
|
78 | method,
|
79 | statusCode,
|
80 | session,
|
81 | headers: {
|
82 |
|
83 | Host: urlObject.host,
|
84 | ...headers,
|
85 | },
|
86 | });
|
87 |
|
88 |
|
89 |
|
90 | req.socket = new stream.Duplex() as any;
|
91 | Object.defineProperty(req.socket, 'encrypted', {
|
92 | writable: false,
|
93 | value: urlObject.protocol === 'https:',
|
94 | });
|
95 |
|
96 | const res = httpMocks.createResponse();
|
97 |
|
98 |
|
99 |
|
100 | res.set = undefined as any;
|
101 |
|
102 | const context = app.createContext(req, res) as MockContext & CustomProperties;
|
103 | context.cookies = createMockCookies(cookies);
|
104 |
|
105 |
|
106 | context.request.body = requestBody;
|
107 |
|
108 | return context;
|
109 | }
|