|
| 1 | +const test = require('ava'); |
| 2 | +const Boom = require('boom'); |
| 3 | + |
| 4 | +const Timeout = require('../'); |
| 5 | + |
| 6 | +const next = () => { |
| 7 | + return new Promise(resolve => { |
| 8 | + resolve(); |
| 9 | + }); |
| 10 | +}; |
| 11 | + |
| 12 | +test('returns itself', t => { |
| 13 | + t.true(new Timeout() instanceof Timeout); |
| 14 | +}); |
| 15 | + |
| 16 | +test('sets a default config object', t => { |
| 17 | + const timeout = new Timeout(); |
| 18 | + t.is(timeout.config.ms, 6000); |
| 19 | + t.is(timeout.config.message, Boom.clientTimeout().message); |
| 20 | + t.is(timeout.config.sendResponse, Boom.clientTimeout); |
| 21 | +}); |
| 22 | + |
| 23 | +test('times out and sends response', async t => { |
| 24 | + const timeout = new Timeout(); |
| 25 | + const ctx = { req: {} }; |
| 26 | + const error = await t.throws( |
| 27 | + timeout.middleware(ctx, () => { |
| 28 | + return new Promise(resolve => { |
| 29 | + setTimeout(resolve, 7000); |
| 30 | + }); |
| 31 | + }) |
| 32 | + ); |
| 33 | + t.true(ctx.req._timeout._called); |
| 34 | + t.is(error.message, Boom.clientTimeout().message); |
| 35 | +}); |
| 36 | + |
| 37 | +test('clears timeout after response', async t => { |
| 38 | + const timeout = new Timeout(); |
| 39 | + const ctx = { req: {} }; |
| 40 | + await timeout.middleware(ctx, next); |
| 41 | + t.false(ctx.req._timeout._called); |
| 42 | +}); |
| 43 | + |
| 44 | +test('clears timeout after error', async t => { |
| 45 | + const timeout = new Timeout(); |
| 46 | + const ctx = { req: {} }; |
| 47 | + const error = await t.throws( |
| 48 | + timeout.middleware(ctx, () => { |
| 49 | + return Promise.reject(new Error('done')); |
| 50 | + }) |
| 51 | + ); |
| 52 | + t.false(ctx.req._timeout._called); |
| 53 | + t.is(error.message, 'done'); |
| 54 | +}); |
| 55 | + |
| 56 | +test('throws error if ms not a number', t => { |
| 57 | + const error = t.throws(() => { |
| 58 | + // eslint-disable-next-line no-new |
| 59 | + new Timeout({ ms: '' }); |
| 60 | + }); |
| 61 | + t.is(error.message, 'timeout `ms` was not a number'); |
| 62 | +}); |
| 63 | + |
| 64 | +test('throws error if message not a string', t => { |
| 65 | + const error = t.throws(() => { |
| 66 | + // eslint-disable-next-line no-new |
| 67 | + new Timeout({ message: false }); |
| 68 | + }); |
| 69 | + t.is(error.message, 'timeout `message` was not a string'); |
| 70 | +}); |
| 71 | + |
| 72 | +test('throws error if sendResponse not a function', t => { |
| 73 | + const error = t.throws(() => { |
| 74 | + // eslint-disable-next-line no-new |
| 75 | + new Timeout({ sendResponse: '' }); |
| 76 | + }); |
| 77 | + t.is(error.message, 'timeout `sendResponse` function is missing'); |
| 78 | +}); |
0 commit comments