compose.test.ts
This file
Path
src/compose.test.ts
94 lines 路 2.4 KiB 路 TypeScript
Last changed by
refactor: compose (#116)Yusuke Wadabefore adoptiona66296b
History of this fileTake it
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495import { compose } from './compose'import { Context } from './context'
type C = { req: Record<string, string> res: Record<string, string>}
describe('compose', () => { const middleware: Function[] = []
const a = async (c: C, next: Function) => { c.req['log'] = 'log' await next() } middleware.push(a)
const b = async (c: C, next: Function) => { await next() c.res['headers'] = 'custom-header' } middleware.push(b)
const handler = async (c: C, next: Function) => { c.req['log'] = `${c.req.log} message` await next() c.res = { message: 'new response' } } middleware.push(handler)
it('Request', async () => { const c: C = { req: {}, res: {} } const composed = compose<C>(middleware) const context = await composed(c) expect(context.req['log']).not.toBeNull() expect(context.req['log']).toBe('log message') }) it('Response', async () => { const c: C = { req: {}, res: {} } const composed = compose<C>(middleware) const context = await composed(c) expect(context.res['headers']).not.toBeNull() expect(context.res['headers']).toBe('custom-header') expect(context.res['message']).toBe('new response') })})
describe('compose with Context', () => { const middleware: Function[] = []
const req = new Request('http://localhost/') const c: Context = new Context(req) const onError = (error: Error, c: Context) => { return c.text('onError', 500) }
it('Error on handler', async () => { const handler = () => { throw new Error() }
const mHandler = async (c: Context, next: Function) => { await next() }
middleware.push(mHandler) middleware.push(handler)
const composed = compose<Context>(middleware, onError) const context = await composed(c) expect(context.res).not.toBeNull() expect(context.res.status).toBe(500) expect(await context.res.text()).toBe('onError') })
it('Error on middleware', async () => { const handler = (c: Context) => { return c.text('OK') }
const mHandler = async () => { throw new Error() }
middleware.push(mHandler) middleware.push(handler)
const composed = compose<Context>(middleware, onError) const context = await composed(c) expect(c.res).not.toBeNull() expect(c.res.status).toBe(500) expect(await context.res.text()).toBe('onError') })})