| 113 | }) |
| 114 | |
| 115 | function testHandlerOrBeforeHandlerHook (test, hookOrHandler) { |
| 116 | const idx = hookOrHandler === class="st">'handler' ? lifecycleHooks.indexOf(class="st">'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(class="st">'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(class="st">'data', (line) => { |
| 130 | t.assert.notStrictEqual(line.level, 40) class="cm">// there are no errors |
| 131 | t.assert.notStrictEqual(line.level, 50) class="cm">// 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 === class="st">'handler') { |
| 137 | app.get(class="st">'/', (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(class="st">'/', (req, reply) => t.assert.fail(class="st">'Handler should not be called')) |
| 147 | } |
| 148 | |
| 149 | nextHooks.forEach(h => { |
| 150 | if (h === class="st">'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: class="st">'GET', |
| 159 | url: class="st">'/' |
| 160 | }).then((res) => { |
| 161 | t.assert.strictEqual(res.statusCode, 200) |
| 162 | t.assert.strictEqual(res.body, `hello from ${hookOrHandler}`) |
| 163 | }) |
| 164 | }) |
| 165 | |
| 166 | test(class="st">'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 | }) |