|
| 1 | +const Koa = require('koa'); |
| 2 | +const Router = require('koa-router'); |
| 3 | +const Boom = require('boom'); |
1 | 4 | const test = require('ava'); |
| 5 | +const request = require('supertest'); |
| 6 | +const koa404Handler = require('..'); |
2 | 7 |
|
3 | | -const koa404Handler = require('../'); |
| 8 | +const ok = ctx => { |
| 9 | + ctx.status = 200; |
| 10 | + ctx.body = { ok: 'ok' }; |
| 11 | +}; |
| 12 | + |
| 13 | +const error = () => { |
| 14 | + throw new Error('Big Bad Error!'); |
| 15 | +}; |
4 | 16 |
|
5 | 17 | test('returns a function', t => { |
6 | 18 | t.true(typeof koa404Handler === 'function'); |
7 | 19 | }); |
| 20 | + |
| 21 | +test.failing('middleware can be added to the app at any stage', async t => { |
| 22 | + const app = new Koa(); |
| 23 | + const router = new Router(); |
| 24 | + |
| 25 | + router.get('/', ok); |
| 26 | + |
| 27 | + // Mount the app's defined and nested routes |
| 28 | + app.use(router.routes()); |
| 29 | + |
| 30 | + // Options method |
| 31 | + app.use( |
| 32 | + router.allowedMethods({ |
| 33 | + throw: true, |
| 34 | + notImplemented: () => new Boom.notImplemented(), // eslint-disable-line new-cap,max-len |
| 35 | + methodNotAllowed: () => new Boom.methodNotAllowed() // eslint-disable-line new-cap,max-len |
| 36 | + }) |
| 37 | + ); |
| 38 | + |
| 39 | + // 404 handler |
| 40 | + app.use(koa404Handler); |
| 41 | + |
| 42 | + const res = await request(app.listen()).options('/'); |
| 43 | + |
| 44 | + t.is(200, res.status); |
| 45 | + t.is(res.body.ok, 'ok'); |
| 46 | +}); |
| 47 | + |
| 48 | +test('emits error on app instance', async t => { |
| 49 | + const app = new Koa(); |
| 50 | + const router = new Router(); |
| 51 | + |
| 52 | + router.get('/', error); |
| 53 | + |
| 54 | + // Mount the app's defined and nested routes |
| 55 | + app.use(router.routes()); |
| 56 | + |
| 57 | + // 404 handler |
| 58 | + app.use(koa404Handler); |
| 59 | + |
| 60 | + app.on('error', error => { |
| 61 | + t.truthy(error); |
| 62 | + t.is(error.message, 'Big Bad Error!'); |
| 63 | + }); |
| 64 | + |
| 65 | + await request(app.listen()).get('/'); |
| 66 | +}); |
0 commit comments