-
-
Notifications
You must be signed in to change notification settings - Fork 137
/
hooks.spec.ts
92 lines (76 loc) 路 2.31 KB
/
hooks.spec.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
// std
import { strictEqual } from 'assert';
// FoalTS
import {
Context,
getHookFunction,
Hook,
HttpResponseBadRequest,
HttpResponseOK,
isHttpResponse,
isHttpResponseBadRequest,
ServiceManager
} from '@foal/core';
describe('[Docs] Architecture > Hooks', () => {
it('Testing Hooks', () => {
// validate-body.hook.ts
function ValidateBody() {
return Hook(ctx => {
if (typeof ctx.request.body.name !== 'string') {
return new HttpResponseBadRequest();
}
});
}
// validate-body.hook.spec.ts
const ctx = new Context({
// fake request object
body: { name: 3 }
});
const hook = getHookFunction(ValidateBody());
const response = hook(ctx, new ServiceManager());
if (!isHttpResponseBadRequest(response)) {
throw new Error('The hook should return an HttpResponseBadRequest object.');
}
});
it('Testing Hook Post Functions', async () => {
// add-xxx-header.hook.ts
function AddXXXHeader() {
return Hook(ctx => response => {
response.setHeader('XXX', 'YYY');
});
}
// add-xxx-header.hook.spec.ts
const ctx = new Context({});
const hook = getHookFunction(AddXXXHeader());
const postHookFunction = await hook(ctx, new ServiceManager());
if (postHookFunction === undefined || isHttpResponse(postHookFunction)) {
throw new Error('The hook should return a post hook function');
}
const response = new HttpResponseOK();
await postHookFunction(response);
strictEqual(response.getHeader('XXX'), 'YYY');
});
it('Testing Hooks Using this', () => {
// validate-param-type.hook.ts
function ValidateParamType() {
return Hook(function(this: any, ctx: Context) {
if (typeof ctx.request.params.id !== this.paramType) {
return new HttpResponseBadRequest();
}
});
}
// validate-param-type.hook.spec.ts
const ctx = new Context({
// fake request object
params: { id: 'xxx' }
});
const controller = {
paramType: 'number'
};
const hook = getHookFunction(ValidateParamType()).bind(controller);
const response = hook(ctx, new ServiceManager());
if (!isHttpResponseBadRequest(response)) {
throw new Error('The hook should return an HttpResponseBadRequest object.');
}
});
});