diff --git a/fastify.js b/fastify.js index eb5d861f428..22a9dadaa56 100644 --- a/fastify.js +++ b/fastify.js @@ -401,11 +401,11 @@ function fastify (options) { try { const dc = require('diagnostics_channel') - const initChannel = dc.channel('fastify.initialized') + const initChannel = dc.channel('fastify.initialization') if (initChannel.hasSubscribers) { initChannel.publish({ fastify }) } - } catch { + } catch (e) { // This only happens if `diagnostics_channel` isn't available, i.e. earlier // versions of Node.js. In that event, we don't care, so ignore the error. } diff --git a/test/diagnostics-channel.test.js b/test/diagnostics-channel.test.js index d5eb390d018..9b8e301cea6 100644 --- a/test/diagnostics-channel.test.js +++ b/test/diagnostics-channel.test.js @@ -2,25 +2,60 @@ const t = require('tap') const test = t.test -let dc -try { - dc = require('diagnostics_channel') -} catch { - // Not available in this version of Node.js - t.skip('diagnostics_channel is not available') - process.exit(0) -} - -test('diagnostics_channel', t => { - t.plan(2) +const proxyquire = require('proxyquire') + +test('diagnostics_channel when present and subscribers', t => { + t.plan(3) let fastifyInHook - const channel = dc.channel('fastify.initialized') - channel.subscribe(function ({ fastify }) { - t.pass('message passed to channel') - fastifyInHook = fastify - }) - const fastify = require('../fastify')() + const dc = { + channel (name) { + t.equal(name, 'fastify.initialization') + return { + hasSubscribers: true, + publish (event) { + t.ok(event.fastify) + fastifyInHook = event.fastify + } + } + }, + '@noCallThru': true + } + + const fastify = proxyquire('../fastify', { + diagnostics_channel: dc + })() t.equal(fastifyInHook, fastify) }) + +test('diagnostics_channel when present and no subscribers', t => { + t.plan(1) + + const dc = { + channel (name) { + t.equal(name, 'fastify.initialization') + return { + hasSubscribers: false, + publish () { + t.fail('publish should not be called') + } + } + }, + '@noCallThru': true + } + + proxyquire('../fastify', { + diagnostics_channel: dc + })() +}) + +test('diagnostics_channel when not present', t => { + t.plan(1) + + t.doesNotThrow(() => { + proxyquire('../fastify', { + diagnostics_channel: null + })() + }) +})