MCPcopy
hub / github.com/fastify/fastify / testBeforeHandlerHook

Function testBeforeHandlerHook

test/route-hooks.test.js:182–390  ·  view source on GitHub ↗
(hook)

Source from the content-addressed store, hash-verified

180}
181
182function testBeforeHandlerHook (hook) {
183 test(`${hook} option should be unique per route`, (t, testDone) => {
184 t.plan(4)
185 const fastify = Fastify()
186
187 fastify.post('/', {
188 [hook]: (req, reply, doneOrPayload, done) => {
189 req.hello = 'earth'
190 endRouteHook(doneOrPayload, done)
191 }
192 }, (req, reply) => {
193 reply.send({ hello: req.hello })
194 })
195
196 fastify.post('/no', (req, reply) => {
197 reply.send(req.body)
198 })
199
200 fastify.inject({
201 method: 'POST',
202 url: '/',
203 payload: { hello: 'world' }
204 }, (err, res) => {
205 t.assert.ifError(err)
206 const payload = JSON.parse(res.payload)
207 t.assert.deepStrictEqual(payload, { hello: 'earth' })
208 })
209
210 fastify.inject({
211 method: 'POST',
212 url: '/no',
213 payload: { hello: 'world' }
214 }, (err, res) => {
215 t.assert.ifError(err)
216 const payload = JSON.parse(res.payload)
217 t.assert.deepStrictEqual(payload, { hello: 'world' })
218 testDone()
219 })
220 })
221
222 test(`${hook} option should handle errors`, (t, testDone) => {
223 t.plan(3)
224 const fastify = Fastify()
225
226 fastify.post('/', {
227 [hook]: (req, reply, doneOrPayload, done) => {
228 endRouteHook(doneOrPayload, done, new Error('kaboom'))
229 }
230 }, (req, reply) => {
231 reply.send(req.body)
232 })
233
234 fastify.inject({
235 method: 'POST',
236 url: '/',
237 payload: { hello: 'world' }
238 }, (err, res) => {
239 t.assert.ifError(err)

Callers 1

Calls 5

endRouteHookFunction · 0.85
sendMethod · 0.80
injectMethod · 0.80
setErrorHandlerMethod · 0.80
codeMethod · 0.80

Tested by

no test coverage detected