1 | 'use strict'
|
2 |
|
3 | const t = require('tap')
|
4 | const test = t.test
|
5 |
|
6 | const { Hooks } = require('../../lib/hooks')
|
7 | const noop = () => {}
|
8 |
|
9 | test('hooks should have 4 array with the registered hooks', t => {
|
10 | const hooks = new Hooks()
|
11 | t.is(typeof hooks, 'object')
|
12 | t.ok(Array.isArray(hooks.onRequest))
|
13 | t.ok(Array.isArray(hooks.onSend))
|
14 | t.ok(Array.isArray(hooks.preParsing))
|
15 | t.ok(Array.isArray(hooks.preValidation))
|
16 | t.ok(Array.isArray(hooks.preHandler))
|
17 | t.ok(Array.isArray(hooks.onResponse))
|
18 | t.ok(Array.isArray(hooks.onError))
|
19 | t.end()
|
20 | })
|
21 |
|
22 | test('hooks.add should add a hook to the given hook', t => {
|
23 | const hooks = new Hooks()
|
24 | hooks.add('onRequest', noop)
|
25 | t.is(hooks.onRequest.length, 1)
|
26 | t.is(typeof hooks.onRequest[0], 'function')
|
27 |
|
28 | hooks.add('preParsing', noop)
|
29 | t.is(hooks.preParsing.length, 1)
|
30 | t.is(typeof hooks.preParsing[0], 'function')
|
31 |
|
32 | hooks.add('preValidation', noop)
|
33 | t.is(hooks.preValidation.length, 1)
|
34 | t.is(typeof hooks.preValidation[0], 'function')
|
35 |
|
36 | hooks.add('preHandler', noop)
|
37 | t.is(hooks.preHandler.length, 1)
|
38 | t.is(typeof hooks.preHandler[0], 'function')
|
39 |
|
40 | hooks.add('onResponse', noop)
|
41 | t.is(hooks.onResponse.length, 1)
|
42 | t.is(typeof hooks.onResponse[0], 'function')
|
43 |
|
44 | hooks.add('onSend', noop)
|
45 | t.is(hooks.onSend.length, 1)
|
46 | t.is(typeof hooks.onSend[0], 'function')
|
47 |
|
48 | hooks.add('onError', noop)
|
49 | t.is(hooks.onError.length, 1)
|
50 | t.is(typeof hooks.onError[0], 'function')
|
51 | t.end()
|
52 | })
|
53 |
|
54 | test('hooks should throw on unexisting handler', t => {
|
55 | t.plan(1)
|
56 | const hooks = new Hooks()
|
57 | try {
|
58 | hooks.add('onUnexistingHook', noop)
|
59 | t.fail()
|
60 | } catch (e) {
|
61 | t.pass()
|
62 | }
|
63 | })
|
64 |
|
65 | test('should throw on wrong parameters', t => {
|
66 | const hooks = new Hooks()
|
67 | t.plan(4)
|
68 | try {
|
69 | hooks.add(null, noop)
|
70 | t.fail()
|
71 | } catch (e) {
|
72 | t.is(e.code, 'FST_ERR_HOOK_INVALID_TYPE')
|
73 | t.is(e.message, 'FST_ERR_HOOK_INVALID_TYPE: The hook name must be a string')
|
74 | }
|
75 |
|
76 | try {
|
77 | hooks.add('', null)
|
78 | t.fail()
|
79 | } catch (e) {
|
80 | t.is(e.code, 'FST_ERR_HOOK_INVALID_HANDLER')
|
81 | t.is(e.message, 'FST_ERR_HOOK_INVALID_HANDLER: The hook callback must be a function')
|
82 | }
|
83 | })
|