-
-
Notifications
You must be signed in to change notification settings - Fork 281
/
PlatformTest.ts
188 lines (168 loc) · 5.36 KB
/
PlatformTest.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import {Type} from "@tsed/core";
import {createContainer, DITest, InjectorService} from "@tsed/di";
import {PlatformBuilder, PlatformType} from "../builder/PlatformBuilder";
import {PlatformContext, PlatformContextOptions} from "../domain/PlatformContext";
import {createInjector} from "../utils/createInjector";
import {PlatformApplication} from "./PlatformApplication";
import {PlatformViews} from "@tsed/platform-views";
import {getConfiguration} from "../utils/getConfiguration";
/**
* @platform
*/
export class PlatformTest extends DITest {
public static platformBuilder: Type<PlatformBuilder<any, any>>;
static async create(options: Partial<TsED.Configuration> = {}) {
DITest.injector = PlatformTest.createInjector(getConfiguration(options, null));
const container = createContainer();
await DITest.injector.load(container);
}
/**
* Create a new injector with the right default services
*/
static createInjector(settings: any = {}): InjectorService {
return createInjector(DITest.configure(settings));
}
/**
* Load the server silently without listening port and configure it on test profile.
* @decorator
* @param mod
* @param settings
* @returns {Promise<void>}
*/
static bootstrap(mod: any, settings: Partial<TsED.Configuration & {listen: boolean}> = {}): () => Promise<void> {
return async function before(): Promise<void> {
let instance: any;
const platform: PlatformType = settings.platform || PlatformTest.platformBuilder;
/* istanbul ignore next */
if (!platform) {
throw new Error(
"Platform type is not specified. Have you added at least `import @tsed/platform-express` (or equivalent) on your Server.ts ?"
);
}
// @ts-ignore
settings = DITest.configure(settings);
instance = await PlatformBuilder.build(platform, mod, settings).bootstrap();
if (!settings.listen) {
await instance.callHook("$beforeListen");
await instance.callHook("$afterListen");
await instance.ready();
} else {
await instance.listen();
}
// used by inject method
DITest.injector = instance.injector;
};
}
/**
* It injects services into the test function where you can alter, spy on, and manipulate them.
*
* The inject function has two parameters
*
* * an array of Service dependency injection tokens,
* * a test function whose parameters correspond exactly to each item in the injection token array.
*
* @param targets
* @param func
*/
static inject<T>(targets: any[], func: (...args: any[]) => Promise<T> | T): () => Promise<T> {
return async (): Promise<T> => {
if (!DITest.hasInjector()) {
await PlatformTest.create();
}
const injector: InjectorService = DITest.injector;
const deps = [];
for (const target of targets) {
deps.push(injector.has(target) ? injector.get(target) : await injector.invoke(target));
}
return await func(...deps);
};
}
/**
* Return the raw application (express or koa).
* Use this callback with SuperTest.
*
* ```typescript
* let request: SuperTest.SuperTest<SuperTest.Test>;
* beforeEach(PlatformTest.bootstrap(Server, {
* mount: {
* "/rest": [ProductsController]
* }
* }));
* beforeEach(() => {
* request = SuperTest(PlatformTest.callback());
* });
* ```
*/
static callback() {
return DITest.injector.get<PlatformApplication>(PlatformApplication)?.callback();
}
static createRequest(options: any = {}): any {
return {
headers: {},
get(key: string) {
return this.headers[key.toLowerCase()];
},
accepts(mime?: string | string[]) {
return require("accepts")(this).types([].concat(mime as never));
},
...options
};
}
static createResponse(options: any = {}): any {
return {
headers: {},
locals: {},
statusCode: 200,
status(code: number) {
this.statusCode = code;
return this;
},
contentType(content: string) {
this.set("content-type", content);
},
contentLength(content: number) {
this.set("content-length", content);
},
redirect(status: number, path: string) {
this.statusCode = status;
this.set("location", path);
},
location(path: string) {
this.set("location", path);
},
get(key: string) {
return this.headers[key.toLowerCase()];
},
getHeaders() {
return this.headers;
},
set(key: string, value: any) {
this.headers[key.toLowerCase()] = value;
return this;
},
send(data: any) {
this.data = data;
},
json(data: any) {
this.data = data;
},
...options
};
}
static createRequestContext(options: Partial<PlatformContextOptions & any> = {}) {
const event = {
request: options?.request?.request || options?.event?.request || PlatformTest.createRequest(),
response: options?.response?.response || options?.event?.response || PlatformTest.createResponse()
};
const ctx = new PlatformContext({
id: "id",
injector: DITest.injector,
logger: DITest.injector.logger,
url: "/",
...options,
event
});
ctx.response.platformViews = PlatformTest.get<PlatformViews>(PlatformViews);
return ctx;
}
}