UNPKG

1.41 kBJavaScriptView Raw
1'use strict'
2
3const http = require('http')
4const test = require('tap').test
5const fastify = require('../')
6
7test('handlers receive correct `this` context', (t) => {
8 t.plan(4)
9
10 // simulate plugin that uses fastify-plugin
11 const plugin = function (instance, opts, next) {
12 instance.decorate('foo', 'foo')
13 next()
14 }
15 plugin[Symbol.for('skip-override')] = true
16
17 const instance = fastify()
18 instance.register(plugin)
19
20 instance.get('/', function (req, reply) {
21 t.ok(this.foo)
22 t.is(this.foo, 'foo')
23 reply.send()
24 })
25
26 instance.listen(0, (err) => {
27 instance.server.unref()
28 if (err) t.threw(err)
29 t.ok(instance.foo)
30 t.is(instance.foo, 'foo')
31
32 const address = `http://127.0.0.1:${instance.server.address().port}/`
33 http.get(address, () => {}).on('error', t.threw)
34 })
35})
36
37test('handlers have access to the internal context', (t) => {
38 t.plan(5)
39
40 const instance = fastify()
41 instance.get('/', { config: { foo: 'bar' } }, function (req, reply) {
42 t.ok(reply.context)
43 t.ok(reply.context.config)
44 t.type(reply.context.config, Object)
45 t.ok(reply.context.config.foo)
46 t.is(reply.context.config.foo, 'bar')
47 reply.send()
48 })
49
50 instance.listen(0, (err) => {
51 instance.server.unref()
52 if (err) t.threw(err)
53 const address = `http://127.0.0.1:${instance.server.address().port}/`
54 http.get(address, () => {}).on('error', t.threw)
55 })
56})