MCPcopy
hub / github.com/fastify/fastify / testHandlerOrBeforeHandlerHook

Function testHandlerOrBeforeHandlerHook

test/skip-reply-send.test.js:115–311  ·  view source on GitHub ↗
(test, hookOrHandler)

Source from the content-addressed store, hash-verified

113})
114
115function testHandlerOrBeforeHandlerHook (test, hookOrHandler) {
116 const idx = hookOrHandler === 'handler' ? lifecycleHooks.indexOf('preHandler') : lifecycleHooks.indexOf(hookOrHandler)
117 const previousHooks = lifecycleHooks.slice(0, idx)
118 const nextHooks = lifecycleHooks.slice(idx + 1)
119
120 describe(`Hijacking inside ${hookOrHandler} skips all the following hooks and handler execution`, () => {
121 test('Sending a response using reply.raw => onResponse hook is called', async (t) => {
122 const stream = split(JSON.parse)
123 const app = Fastify({
124 logger: {
125 stream
126 }
127 })
128
129 stream.on('data', (line) => {
130 t.assert.notStrictEqual(line.level, 40) // there are no errors
131 t.assert.notStrictEqual(line.level, 50) // there are no errors
132 })
133
134 previousHooks.forEach(h => app.addHook(h, async (req, reply) => t.assert.ok(`${h} should be called`)))
135
136 if (hookOrHandler === 'handler') {
137 app.get('/', (req, reply) => {
138 reply.hijack()
139 reply.raw.end(`hello from ${hookOrHandler}`)
140 })
141 } else {
142 app.addHook(hookOrHandler, async (req, reply) => {
143 reply.hijack()
144 reply.raw.end(`hello from ${hookOrHandler}`)
145 })
146 app.get('/', (req, reply) => t.assert.fail('Handler should not be called'))
147 }
148
149 nextHooks.forEach(h => {
150 if (h === 'onResponse') {
151 app.addHook(h, async (req, reply) => t.assert.ok(`${h} should be called`))
152 } else {
153 app.addHook(h, async (req, reply) => t.assert.fail(`${h} should not be called`))
154 }
155 })
156
157 await app.inject({
158 method: 'GET',
159 url: '/'
160 }).then((res) => {
161 t.assert.strictEqual(res.statusCode, 200)
162 t.assert.strictEqual(res.body, `hello from ${hookOrHandler}`)
163 })
164 })
165
166 test('Sending a response using req.socket => onResponse not called', (t, testDone) => {
167 const stream = split(JSON.parse)
168 const app = Fastify({
169 logger: {
170 stream
171 }
172 })

Callers 1

Calls 9

addHookMethod · 0.80
hijackMethod · 0.80
thenMethod · 0.80
injectMethod · 0.80
afterMethod · 0.80
closeMethod · 0.80
writeMethod · 0.80
listenMethod · 0.80
sendMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…