Use test directory (#19)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent dbb5016 · Browse files · 21 files·+614 added−614 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
21 files+614 added−614 removed
- tests:+543 added−543 removed
- other:+71 added−71 removed
Provenance
- Commit
ce6bd99- Tree
4caf058- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
dbb5016
21 files changed+614 added−614 removed
added:src/middleware/logger/logger.js+63 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263const { getPathFromURL } = require('../../util')
const humanize = (n, opts) => { const options = opts || {} const d = options.delimiter || ',' const s = options.separator || '.' n = n.toString().split('.') n[0] = n[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + d) return n.join(s)}
const time = (start) => { const delta = Date.now() - start return humanize(delta < 10000 ? delta + 'ms' : Math.round(delta / 1000) + 's')}
const LogPrefix = { Outgoing: '-->', Incoming: '<--', Error: 'xxx',}
const colorStatus = (status) => { const out = { 7: `\x1b[35m${status}\x1b[0m`, 5: `\x1b[31m${status}\x1b[0m`, 4: `\x1b[33m${status}\x1b[0m`, 3: `\x1b[36m${status}\x1b[0m`, 2: `\x1b[32m${status}\x1b[0m`, 1: `\x1b[32m${status}\x1b[0m`, 0: `\x1b[33m${status}\x1b[0m`, } return out[(status / 100) | 0]}function log(fn, prefix, method, path, status, elasped) { const out = prefix === LogPrefix.Incoming ? ` ${prefix} ${method} ${path}` : ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elasped}` fn(out)}
const logger = (fn = console.log) => { return async (c, next) => { const { method } = c.req const path = getPathFromURL(c.req.url)
log(fn, LogPrefix.Incoming, method, path)
const start = Date.now()
try { await next() } catch (e) { log(fn, LogPrefix.Error, method, path, c.res.status || 500, time(start)) throw e }
log(fn, LogPrefix.Outgoing, method, path, c.res.status, time(start)) }}
module.exports = loggeradded:src/middleware/logger/logger.test.js+36 added
123456789101112131415161718192021222324252627282930313233343536const { makeEdgeEnv } = require('edge-mock')const { Hono, Middleware } = require('../../hono')
makeEdgeEnv()
describe('Logger by Middleware', () => { const app = new Hono()
let log = '' const logFn = (str) => { log = str }
app.use('*', Middleware.logger(logFn)) app.get('/', () => new Response('root'))
it('Log status 200', async () => { const req = new Request('/') const res = await app.dispatch(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(log.startsWith(' --> GET / \x1b[32m200\x1b[0m')).toBe(true) })
it('Log status 404', async () => { app.notFound = () => { return new Response('Default 404 Nout Found', { status: 404 }) }
const req = new Request('/notfound') const res = await app.dispatch(req) expect(res).not.toBeNull() expect(res.status).toBe(404) expect(log.startsWith(' --> GET /notfound \x1b[33m404\x1b[0m')).toBe(true) })})added:src/middleware/poweredBy/poweredBy.js+6 added
123456const poweredBy = async (c, next) => { await next() await c.res.headers.append('X-Powered-By', 'Hono')}
module.exports = poweredByadded:src/middleware/poweredBy/poweredBy.test.js+19 added
12345678910111213141516171819const { makeEdgeEnv } = require('edge-mock')const { Hono, Middleware } = require('../../hono')
makeEdgeEnv()
describe('Powered by Middleware', () => { const app = new Hono()
app.use('*', Middleware.poweredBy) app.get('/', () => new Response('root'))
it('Response headers include X-Powered-By', async () => { let req = new Request('/') let res = await app.dispatch(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(res.headers.get('X-Powered-By')).toBe('Hono') })})deleted:src/middleware/logger.js-63 removed
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263const { getPathFromURL } = require('../util')
const humanize = (n, opts) => { const options = opts || {} const d = options.delimiter || ',' const s = options.separator || '.' n = n.toString().split('.') n[0] = n[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + d) return n.join(s)}
const time = (start) => { const delta = Date.now() - start return humanize(delta < 10000 ? delta + 'ms' : Math.round(delta / 1000) + 's')}
const LogPrefix = { Outgoing: '-->', Incoming: '<--', Error: 'xxx',}
const colorStatus = (status) => { const out = { 7: `\x1b[35m${status}\x1b[0m`, 5: `\x1b[31m${status}\x1b[0m`, 4: `\x1b[33m${status}\x1b[0m`, 3: `\x1b[36m${status}\x1b[0m`, 2: `\x1b[32m${status}\x1b[0m`, 1: `\x1b[32m${status}\x1b[0m`, 0: `\x1b[33m${status}\x1b[0m`, } return out[(status / 100) | 0]}function log(fn, prefix, method, path, status, elasped) { const out = prefix === LogPrefix.Incoming ? ` ${prefix} ${method} ${path}` : ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elasped}` fn(out)}
const logger = (fn = console.log) => { return async (c, next) => { const { method } = c.req const path = getPathFromURL(c.req.url)
log(fn, LogPrefix.Incoming, method, path)
const start = Date.now()
try { await next() } catch (e) { log(fn, LogPrefix.Error, method, path, c.res.status || 500, time(start)) throw e }
log(fn, LogPrefix.Outgoing, method, path, c.res.status, time(start)) }}
module.exports = loggerdeleted:src/middleware/logger.test.js-36 removed
123456789101112131415161718192021222324252627282930313233343536const { makeEdgeEnv } = require('edge-mock')const { Hono, Middleware } = require('../hono')
makeEdgeEnv()
describe('Logger by Middleware', () => { const app = new Hono()
let log = '' const logFn = (str) => { log = str }
app.use('*', Middleware.logger(logFn)) app.get('/', () => new Response('root'))
it('Log status 200', async () => { const req = new Request('/') const res = await app.dispatch(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(log.startsWith(' --> GET / \x1b[32m200\x1b[0m')).toBe(true) })
it('Log status 404', async () => { app.notFound = () => { return new Response('Default 404 Nout Found', { status: 404 }) }
const req = new Request('/notfound') const res = await app.dispatch(req) expect(res).not.toBeNull() expect(res.status).toBe(404) expect(log.startsWith(' --> GET /notfound \x1b[33m404\x1b[0m')).toBe(true) })})deleted:src/middleware/poweredBy.js-6 removed
123456const poweredBy = async (c, next) => { await next() await c.res.headers.append('X-Powered-By', 'Hono')}
module.exports = poweredBydeleted:src/middleware/poweredBy.test.js-19 removed
12345678910111213141516171819const { makeEdgeEnv } = require('edge-mock')const { Hono, Middleware } = require('../hono')
makeEdgeEnv()
describe('Powered by Middleware', () => { const app = new Hono()
app.use('*', Middleware.poweredBy) app.get('/', () => new Response('root'))
it('Response headers include X-Powered-By', async () => { let req = new Request('/') let res = await app.dispatch(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(res.headers.get('X-Powered-By')).toBe('Hono') })})deleted:src/compose.test.js-42 removed
1-const compose = require('./compose')2-3-describe('compose middleware', () => {4- const middleware = []5-6- const a = async (c, next) => {7- c.req['log'] = 'log'8- await next()9- }10- middleware.push(a)11-12- const b = async (c, next) => {13- await next()14- c.res['header'] = `${c.res.header}-custom-header`15- }16- middleware.push(b)17-18- const handler = async (c, next) => {19- c.req['log'] = `${c.req.log} message`20- await next()21- c.res = { message: 'new response' }22- }23- middleware.push(handler)24-25- const request = {}26- const response = {}27-28- it('Request', async () => {29- const c = { req: request, res: response }30- const composed = compose(middleware)31- await composed(c)32- expect(c.req['log']).not.toBeNull()33- expect(c.req['log']).toBe('log message')34- })35- it('Response', async () => {36- const c = { req: request, res: response }37- const composed = compose(middleware)38- await composed(c)39- expect(c.res['header']).not.toBeNull()40- expect(c.res['message']).toBe('new response')41- })42-})deleted:src/hono.test.js-160 removed
1-const { makeEdgeEnv } = require('edge-mock')2-const { Hono } = require('./hono')3-4-makeEdgeEnv()5-6-describe('GET Request', () => {7- const app = new Hono()8-9- app.get('/hello', () => {10- return new Response('hello', {11- status: 200,12- })13- })14- app.notFound = () => {15- return new Response('not found', {16- status: 404,17- })18- }19- it('GET /hello is ok', async () => {20- let req = new Request('/hello')21- let res = await app.dispatch(req)22- expect(res).not.toBeNull()23- expect(res.status).toBe(200)24- expect(await res.text()).toBe('hello')25- })26- it('GET / is not found', async () => {27- let req = new Request('/')28- let res = await app.dispatch(req)29- expect(res).not.toBeNull()30- expect(res.status).toBe(404)31- })32-})33-34-describe('params and query', () => {35- const app = new Hono()36-37- app.get('/entry/:id', async (c) => {38- const id = await c.req.params('id')39- return new Response(`id is ${id}`, {40- status: 200,41- })42- })43-44- app.get('/search', async (c) => {45- const name = await c.req.query('name')46- return new Response(`name is ${name}`, {47- status: 200,48- })49- })50-51- it('params of /entry/:id is found', async () => {52- let req = new Request('/entry/123')53- let res = await app.dispatch(req)54- expect(res.status).toBe(200)55- expect(await res.text()).toBe('id is 123')56- })57- it('query of /search?name=sam is found', async () => {58- let req = new Request('/search?name=sam')59- let res = await app.dispatch(req)60- expect(res.status).toBe(200)61- expect(await res.text()).toBe('name is sam')62- })63-})64-65-describe('Middleware', () => {66- const app = new Hono()67-68- const logger = async (c, next) => {69- console.log(`${c.req.method} : ${c.req.url}`)70- await next()71- }72-73- const rootHeader = async (c, next) => {74- await next()75- await c.res.headers.append('x-custom', 'root')76- }77-78- const customHeader = async (c, next) => {79- await next()80- await c.res.headers.append('x-message', 'custom-header')81- }82- const customHeader2 = async (c, next) => {83- await next()84- c.res.headers.append('x-message-2', 'custom-header-2')85- }86-87- app.use('*', logger)88- app.use('*', rootHeader)89- app.use('/hello', customHeader)90- app.use('/hello/*', customHeader2)91-92- app.get('/hello', () => {93- return new Response('hello')94- })95- app.get('/hello/:message', (c) => {96- const message = c.req.params('message')97- return new Response(`${message}`)98- })99-100- it('logging and custom header', async () => {101- let req = new Request('/hello')102- let res = await app.dispatch(req)103- expect(res.status).toBe(200)104- expect(await res.text()).toBe('hello')105- expect(await res.headers.get('x-custom')).toBe('root')106- expect(await res.headers.get('x-message')).toBe('custom-header')107- expect(await res.headers.get('x-message-2')).toBe('custom-header-2')108- })109-110- it('logging and custom header with named params', async () => {111- let req = new Request('/hello/message')112- let res = await app.dispatch(req)113- expect(res.status).toBe(200)114- expect(await res.text()).toBe('message')115- expect(await res.headers.get('x-custom')).toBe('root')116- expect(await res.headers.get('x-message-2')).toBe('custom-header-2')117- })118-})119-120-describe('Custom 404', () => {121- const app = new Hono()122-123- const customNotFound = async (c, next) => {124- await next()125- if (c.res.status === 404) {126- c.res = new Response('Custom 404 Not Found', { status: 404 })127- }128- }129-130- app.notFound = () => {131- return new Response('Default 404 Nout Found', { status: 404 })132- }133-134- app.use('*', customNotFound)135- app.get('/hello', () => {136- return new Response('hello')137- })138- it('Custom 404 Not Found', async () => {139- let req = new Request('/hello')140- let res = await app.dispatch(req)141- expect(res.status).toBe(200)142- req = new Request('/foo')143- res = await app.dispatch(req)144- expect(res.status).toBe(404)145- expect(await res.text()).toBe('Custom 404 Not Found')146- })147-})148-149-describe('Error Handling', () => {150- const app = new Hono()151-152- it('Middleware must be async function', () => {153- expect(() => {154- app.use('*', {})155- }).toThrow(TypeError)156- expect(() => {157- app.use('*', () => '')158- }).toThrow(TypeError)159- })160-})modified:src/middleware.js+2 added-2 removed
1 const defaultFilter = require('./middleware/defaultFilter')2-const poweredBy = require('./middleware/poweredBy')3-const logger = require('./middleware/logger')2+const poweredBy = require('./middleware/poweredBy/poweredBy')3+const logger = require('./middleware/logger/logger')4 5 function Middleware() {}6 7 Middleware.defaultFilter = defaultFilter4 unmodified linesdeleted:src/middleware.test.js-19 removed
1-const { makeEdgeEnv } = require('edge-mock')2-const { Hono, Middleware } = require('./hono')3-4-makeEdgeEnv()5-6-describe('Builtin Middleware', () => {7- const app = new Hono()8-9- app.use('*', Middleware.poweredBy)10- app.get('/', () => new Response('root'))11-12- it('Builtin Powered By Middleware', async () => {13- let req = new Request('/')14- let res = await app.dispatch(req)15- expect(res).not.toBeNull()16- expect(res.status).toBe(200)17- expect(res.headers.get('X-Powered-By')).toBe('Hono')18- })19-})deleted:src/node.test.js-135 removed
1-const Node = require('./node')2-3-describe('Root Node', () => {4- const node = new Node()5- node.insert('get', '/', 'get root')6- it('get /', () => {7- let res = node.search('get', '/')8- expect(res).not.toBeNull()9- expect(res.handler).toBe('get root')10- expect(node.search('get', '/hello')).toBeNull()11- })12-})13-14-describe('Root Node id not defined', () => {15- const node = new Node()16- node.insert('get', '/hello', 'get hello')17- it('get /', () => {18- expect(node.search('get', '/')).toBeNull()19- })20-})21-22-describe('All with *', () => {23- const node = new Node()24- node.insert('get', '*', 'get all')25- it('get /', () => {26- expect(node.search('get', '/')).not.toBeNull()27- expect(node.search('get', '/hello')).not.toBeNull()28- })29-})30-31-describe('Basic Usage', () => {32- const node = new Node()33- node.insert('get', '/hello', 'get hello')34- node.insert('post', '/hello', 'post hello')35- node.insert('get', '/hello/foo', 'get hello foo')36-37- it('get, post /hello', () => {38- expect(node.search('get', '/')).toBeNull()39- expect(node.search('post', '/')).toBeNull()40-41- expect(node.search('get', '/hello').handler).toBe('get hello')42- expect(node.search('post', '/hello').handler).toBe('post hello')43- expect(node.search('put', '/hello')).toBeNull()44- })45- it('get /nothing', () => {46- expect(node.search('get', '/nothing')).toBeNull()47- })48- it('/hello/foo, /hello/bar', () => {49- expect(node.search('get', '/hello/foo').handler).toBe('get hello foo')50- expect(node.search('post', '/hello/foo')).toBeNull()51- expect(node.search('get', '/hello/bar')).toBeNull()52- })53- it('/hello/foo/bar', () => {54- expect(node.search('get', '/hello/foo/bar')).toBeNull()55- })56-})57-58-describe('Name path', () => {59- const node = new Node()60- it('get /entry/123', () => {61- node.insert('get', '/entry/:id', 'get entry')62- let res = node.search('get', '/entry/123')63- expect(res).not.toBeNull()64- expect(res.handler).toBe('get entry')65- expect(res.params).not.toBeNull()66- expect(res.params['id']).toBe('123')67- expect(res.params['id']).not.toBe('1234')68- })69-70- it('get /entry/456/comment', () => {71- node.insert('get', '/entry/:id', 'get entry')72- let res = node.search('get', '/entry/456/comment')73- expect(res).toBeNull()74- })75-76- it('get /entry/789/comment/123', () => {77- node.insert('get', '/entry/:id/comment/:comment_id', 'get comment')78- let res = node.search('get', '/entry/789/comment/123')79- expect(res).not.toBeNull()80- expect(res.handler).toBe('get comment')81- expect(res.params['id']).toBe('789')82- expect(res.params['comment_id']).toBe('123')83- })84-85- it('get /map/:location/events', () => {86- node.insert('get', '/map/:location/events', 'get events')87- let res = node.search('get', '/map/yokohama/events')88- expect(res).not.toBeNull()89- expect(res.handler).toBe('get events')90- expect(res.params['location']).toBe('yokohama')91- })92-})93-94-describe('Wildcard', () => {95- const node = new Node()96- it('/wildcard-abc/xxxxxx/wildcard-efg', () => {97- node.insert('get', '/wildcard-abc/*/wildcard-efg', 'wildcard')98- let res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg')99- expect(res).not.toBeNull()100- expect(res.handler).toBe('wildcard')101- })102-})103-104-describe('Regexp', () => {105- const node = new Node()106- node.insert('get', '/regex-abc/:id{[0-9]+}/comment/:comment_id{[a-z]+}', 'regexp')107- it('/regexp-abc/123/comment/abc', () => {108- res = node.search('get', '/regex-abc/123/comment/abc')109- expect(res).not.toBeNull()110- expect(res.handler).toBe('regexp')111- expect(res.params['id']).toBe('123')112- expect(res.params['comment_id']).toBe('abc')113- })114- it('/regexp-abc/abc', () => {115- res = node.search('get', '/regex-abc/abc')116- expect(res).toBeNull()117- })118- it('/regexp-abc/123/comment/123', () => {119- res = node.search('get', '/regex-abc/123/comment/123')120- expect(res).toBeNull()121- })122-})123-124-describe('All', () => {125- const node = new Node()126- node.insert('ALL', '/all-methods', 'all methods') // ALL127- it('/all-methods', () => {128- res = node.search('get', '/all-methods')129- expect(res).not.toBeNull()130- expect(res.handler).toBe('all methods')131- res = node.search('put', '/all-methods')132- expect(res).not.toBeNull()133- expect(res.handler).toBe('all methods')134- })135-})deleted:src/router.test.js-88 removed
1-const { Hono } = require('./hono')2-3-describe('Basic Usage', () => {4- const router = new Hono()5-6- it('get, post hello', async () => {7- router.get('/hello', 'get hello')8- router.post('/hello', 'post hello')9-10- let res = await router.matchRoute('GET', '/hello')11- expect(res).not.toBeNull()12- expect(res.handler[0]).toBe('get hello')13-14- res = await router.matchRoute('POST', '/hello')15- expect(res).not.toBeNull()16- expect(res.handler[0]).toBe('post hello')17-18- res = await router.matchRoute('PUT', '/hello')19- expect(res).toBeNull()20-21- res = await router.matchRoute('GET', '/')22- expect(res).toBeNull()23- })24-})25-26-describe('Complex', () => {27- let router = new Hono()28-29- it('Named Param', async () => {30- router.get('/entry/:id', 'get entry')31- res = await router.matchRoute('GET', '/entry/123')32- expect(res).not.toBeNull()33- expect(res.handler[0]).toBe('get entry')34- expect(res.params['id']).toBe('123')35- })36-37- it('Wildcard', async () => {38- router.get('/wild/*/card', 'get wildcard')39- res = await router.matchRoute('GET', '/wild/xxx/card')40- expect(res).not.toBeNull()41- expect(res.handler[0]).toBe('get wildcard')42- })43-44- it('Regexp', async () => {45- router.get('/post/:date{[0-9]+}/:title{[a-z]+}', 'get post')46- res = await router.matchRoute('GET', '/post/20210101/hello')47- expect(res).not.toBeNull()48- expect(res.handler[0]).toBe('get post')49- expect(res.params['date']).toBe('20210101')50- expect(res.params['title']).toBe('hello')51- res = await router.matchRoute('GET', '/post/onetwothree')52- expect(res).toBeNull()53- res = await router.matchRoute('GET', '/post/123/123')54- expect(res).toBeNull()55- })56-})57-58-describe('Chained Route', () => {59- let router = new Hono()60-61- it('Return rooter object', async () => {62- router = router.patch('/hello', 'patch hello')63- expect(router).not.toBeNull()64- router = router.delete('/hello', 'delete hello')65- res = await router.matchRoute('DELETE', '/hello')66- expect(res).not.toBeNull()67- expect(res.handler[0]).toBe('delete hello')68- })69-70- it('Chain with route method', async () => {71- router.route('/api/book').get('get book').post('post book').put('put book')72-73- res = await router.matchRoute('GET', '/api/book')74- expect(res).not.toBeNull()75- expect(res.handler[0]).toBe('get book')76-77- res = await router.matchRoute('POST', '/api/book')78- expect(res).not.toBeNull()79- expect(res.handler[0]).toBe('post book')80-81- res = await router.matchRoute('PUT', '/api/book')82- expect(res).not.toBeNull()83- expect(res.handler[0]).toBe('put book')84-85- res = await router.matchRoute('DELETE', '/api/book')86- expect(res).toBeNull()87- })88-})deleted:src/util.test.js-44 removed
1-const { splitPath, getPattern, getPathFromURL } = require('./util')2-3-describe('Utility methods', () => {4- it('splitPath', () => {5- let ps = splitPath('/')6- expect(ps[0]).toBe('')7- ps = splitPath('/hello')8- expect(ps[0]).toBe('hello')9- ps = splitPath('*')10- expect(ps[0]).toBe('*')11- ps = splitPath('/wildcard-abc/*/wildcard-efg')12- expect(ps[0]).toBe('wildcard-abc')13- expect(ps[1]).toBe('*')14- expect(ps[2]).toBe('wildcard-efg')15- ps = splitPath('/map/:location/events')16- expect(ps[0]).toBe('map')17- expect(ps[1]).toBe(':location')18- expect(ps[2]).toBe('events')19- })20-21- it('getPattern', () => {22- let res = getPattern(':id')23- expect(res[0]).toBe('id')24- expect(res[1]).toBe('(.+)')25- res = getPattern(':id{[0-9]+}')26- expect(res[0]).toBe('id')27- expect(res[1]).toBe('([0-9]+)')28- })29-30- it('getPathFromURL', () => {31- let path = getPathFromURL('https://example.com/')32- expect(path).toBe('/')33- path = getPathFromURL('https://example.com/hello')34- expect(path).toBe('/hello')35- path = getPathFromURL('https://example.com/hello/hey')36- expect(path).toBe('/hello/hey')37- path = getPathFromURL('https://example.com/hello?name=foo')38- expect(path).toBe('/hello')39- path = getPathFromURL('https://example.com/hello/hey?name=foo&name=bar')40- expect(path).toBe('/hello/hey')41- path = getPathFromURL('https://example.com/hello/hey#fragment')42- expect(path).toBe('/hello/hey')43- })44-})added:test/compose.test.js+42 added
1+const compose = require('../src/compose')2+3+describe('compose middleware', () => {4+ const middleware = []5+6+ const a = async (c, next) => {7+ c.req['log'] = 'log'8+ await next()9+ }10+ middleware.push(a)11+12+ const b = async (c, next) => {13+ await next()14+ c.res['header'] = `${c.res.header}-custom-header`15+ }16+ middleware.push(b)17+18+ const handler = async (c, next) => {19+ c.req['log'] = `${c.req.log} message`20+ await next()21+ c.res = { message: 'new response' }22+ }23+ middleware.push(handler)24+25+ const request = {}26+ const response = {}27+28+ it('Request', async () => {29+ const c = { req: request, res: response }30+ const composed = compose(middleware)31+ await composed(c)32+ expect(c.req['log']).not.toBeNull()33+ expect(c.req['log']).toBe('log message')34+ })35+ it('Response', async () => {36+ const c = { req: request, res: response }37+ const composed = compose(middleware)38+ await composed(c)39+ expect(c.res['header']).not.toBeNull()40+ expect(c.res['message']).toBe('new response')41+ })42+})added:test/hono.test.js+160 added
1+const { makeEdgeEnv } = require('edge-mock')2+const { Hono } = require('../src/hono')3+4+makeEdgeEnv()5+6+describe('GET Request', () => {7+ const app = new Hono()8+9+ app.get('/hello', () => {10+ return new Response('hello', {11+ status: 200,12+ })13+ })14+ app.notFound = () => {15+ return new Response('not found', {16+ status: 404,17+ })18+ }19+ it('GET /hello is ok', async () => {20+ let req = new Request('/hello')21+ let res = await app.dispatch(req)22+ expect(res).not.toBeNull()23+ expect(res.status).toBe(200)24+ expect(await res.text()).toBe('hello')25+ })26+ it('GET / is not found', async () => {27+ let req = new Request('/')28+ let res = await app.dispatch(req)29+ expect(res).not.toBeNull()30+ expect(res.status).toBe(404)31+ })32+})33+34+describe('params and query', () => {35+ const app = new Hono()36+37+ app.get('/entry/:id', async (c) => {38+ const id = await c.req.params('id')39+ return new Response(`id is ${id}`, {40+ status: 200,41+ })42+ })43+44+ app.get('/search', async (c) => {45+ const name = await c.req.query('name')46+ return new Response(`name is ${name}`, {47+ status: 200,48+ })49+ })50+51+ it('params of /entry/:id is found', async () => {52+ let req = new Request('/entry/123')53+ let res = await app.dispatch(req)54+ expect(res.status).toBe(200)55+ expect(await res.text()).toBe('id is 123')56+ })57+ it('query of /search?name=sam is found', async () => {58+ let req = new Request('/search?name=sam')59+ let res = await app.dispatch(req)60+ expect(res.status).toBe(200)61+ expect(await res.text()).toBe('name is sam')62+ })63+})64+65+describe('Middleware', () => {66+ const app = new Hono()67+68+ const logger = async (c, next) => {69+ console.log(`${c.req.method} : ${c.req.url}`)70+ await next()71+ }72+73+ const rootHeader = async (c, next) => {74+ await next()75+ await c.res.headers.append('x-custom', 'root')76+ }77+78+ const customHeader = async (c, next) => {79+ await next()80+ await c.res.headers.append('x-message', 'custom-header')81+ }82+ const customHeader2 = async (c, next) => {83+ await next()84+ c.res.headers.append('x-message-2', 'custom-header-2')85+ }86+87+ app.use('*', logger)88+ app.use('*', rootHeader)89+ app.use('/hello', customHeader)90+ app.use('/hello/*', customHeader2)91+92+ app.get('/hello', () => {93+ return new Response('hello')94+ })95+ app.get('/hello/:message', (c) => {96+ const message = c.req.params('message')97+ return new Response(`${message}`)98+ })99+100+ it('logging and custom header', async () => {101+ let req = new Request('/hello')102+ let res = await app.dispatch(req)103+ expect(res.status).toBe(200)104+ expect(await res.text()).toBe('hello')105+ expect(await res.headers.get('x-custom')).toBe('root')106+ expect(await res.headers.get('x-message')).toBe('custom-header')107+ expect(await res.headers.get('x-message-2')).toBe('custom-header-2')108+ })109+110+ it('logging and custom header with named params', async () => {111+ let req = new Request('/hello/message')112+ let res = await app.dispatch(req)113+ expect(res.status).toBe(200)114+ expect(await res.text()).toBe('message')115+ expect(await res.headers.get('x-custom')).toBe('root')116+ expect(await res.headers.get('x-message-2')).toBe('custom-header-2')117+ })118+})119+120+describe('Custom 404', () => {121+ const app = new Hono()122+123+ const customNotFound = async (c, next) => {124+ await next()125+ if (c.res.status === 404) {126+ c.res = new Response('Custom 404 Not Found', { status: 404 })127+ }128+ }129+130+ app.notFound = () => {131+ return new Response('Default 404 Nout Found', { status: 404 })132+ }133+134+ app.use('*', customNotFound)135+ app.get('/hello', () => {136+ return new Response('hello')137+ })138+ it('Custom 404 Not Found', async () => {139+ let req = new Request('/hello')140+ let res = await app.dispatch(req)141+ expect(res.status).toBe(200)142+ req = new Request('/foo')143+ res = await app.dispatch(req)144+ expect(res.status).toBe(404)145+ expect(await res.text()).toBe('Custom 404 Not Found')146+ })147+})148+149+describe('Error Handling', () => {150+ const app = new Hono()151+152+ it('Middleware must be async function', () => {153+ expect(() => {154+ app.use('*', {})155+ }).toThrow(TypeError)156+ expect(() => {157+ app.use('*', () => '')158+ }).toThrow(TypeError)159+ })160+})added:test/middleware.test.js+19 added
1+const { makeEdgeEnv } = require('edge-mock')2+const { Hono, Middleware } = require('../src/hono')3+4+makeEdgeEnv()5+6+describe('Builtin Middleware', () => {7+ const app = new Hono()8+9+ app.use('*', Middleware.poweredBy)10+ app.get('/', () => new Response('root'))11+12+ it('Builtin Powered By Middleware', async () => {13+ let req = new Request('/')14+ let res = await app.dispatch(req)15+ expect(res).not.toBeNull()16+ expect(res.status).toBe(200)17+ expect(res.headers.get('X-Powered-By')).toBe('Hono')18+ })19+})added:test/node.test.js+135 added
1+const Node = require('../src/node')2+3+describe('Root Node', () => {4+ const node = new Node()5+ node.insert('get', '/', 'get root')6+ it('get /', () => {7+ let res = node.search('get', '/')8+ expect(res).not.toBeNull()9+ expect(res.handler).toBe('get root')10+ expect(node.search('get', '/hello')).toBeNull()11+ })12+})13+14+describe('Root Node id not defined', () => {15+ const node = new Node()16+ node.insert('get', '/hello', 'get hello')17+ it('get /', () => {18+ expect(node.search('get', '/')).toBeNull()19+ })20+})21+22+describe('All with *', () => {23+ const node = new Node()24+ node.insert('get', '*', 'get all')25+ it('get /', () => {26+ expect(node.search('get', '/')).not.toBeNull()27+ expect(node.search('get', '/hello')).not.toBeNull()28+ })29+})30+31+describe('Basic Usage', () => {32+ const node = new Node()33+ node.insert('get', '/hello', 'get hello')34+ node.insert('post', '/hello', 'post hello')35+ node.insert('get', '/hello/foo', 'get hello foo')36+37+ it('get, post /hello', () => {38+ expect(node.search('get', '/')).toBeNull()39+ expect(node.search('post', '/')).toBeNull()40+41+ expect(node.search('get', '/hello').handler).toBe('get hello')42+ expect(node.search('post', '/hello').handler).toBe('post hello')43+ expect(node.search('put', '/hello')).toBeNull()44+ })45+ it('get /nothing', () => {46+ expect(node.search('get', '/nothing')).toBeNull()47+ })48+ it('/hello/foo, /hello/bar', () => {49+ expect(node.search('get', '/hello/foo').handler).toBe('get hello foo')50+ expect(node.search('post', '/hello/foo')).toBeNull()51+ expect(node.search('get', '/hello/bar')).toBeNull()52+ })53+ it('/hello/foo/bar', () => {54+ expect(node.search('get', '/hello/foo/bar')).toBeNull()55+ })56+})57+58+describe('Name path', () => {59+ const node = new Node()60+ it('get /entry/123', () => {61+ node.insert('get', '/entry/:id', 'get entry')62+ let res = node.search('get', '/entry/123')63+ expect(res).not.toBeNull()64+ expect(res.handler).toBe('get entry')65+ expect(res.params).not.toBeNull()66+ expect(res.params['id']).toBe('123')67+ expect(res.params['id']).not.toBe('1234')68+ })69+70+ it('get /entry/456/comment', () => {71+ node.insert('get', '/entry/:id', 'get entry')72+ let res = node.search('get', '/entry/456/comment')73+ expect(res).toBeNull()74+ })75+76+ it('get /entry/789/comment/123', () => {77+ node.insert('get', '/entry/:id/comment/:comment_id', 'get comment')78+ let res = node.search('get', '/entry/789/comment/123')79+ expect(res).not.toBeNull()80+ expect(res.handler).toBe('get comment')81+ expect(res.params['id']).toBe('789')82+ expect(res.params['comment_id']).toBe('123')83+ })84+85+ it('get /map/:location/events', () => {86+ node.insert('get', '/map/:location/events', 'get events')87+ let res = node.search('get', '/map/yokohama/events')88+ expect(res).not.toBeNull()89+ expect(res.handler).toBe('get events')90+ expect(res.params['location']).toBe('yokohama')91+ })92+})93+94+describe('Wildcard', () => {95+ const node = new Node()96+ it('/wildcard-abc/xxxxxx/wildcard-efg', () => {97+ node.insert('get', '/wildcard-abc/*/wildcard-efg', 'wildcard')98+ let res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg')99+ expect(res).not.toBeNull()100+ expect(res.handler).toBe('wildcard')101+ })102+})103+104+describe('Regexp', () => {105+ const node = new Node()106+ node.insert('get', '/regex-abc/:id{[0-9]+}/comment/:comment_id{[a-z]+}', 'regexp')107+ it('/regexp-abc/123/comment/abc', () => {108+ res = node.search('get', '/regex-abc/123/comment/abc')109+ expect(res).not.toBeNull()110+ expect(res.handler).toBe('regexp')111+ expect(res.params['id']).toBe('123')112+ expect(res.params['comment_id']).toBe('abc')113+ })114+ it('/regexp-abc/abc', () => {115+ res = node.search('get', '/regex-abc/abc')116+ expect(res).toBeNull()117+ })118+ it('/regexp-abc/123/comment/123', () => {119+ res = node.search('get', '/regex-abc/123/comment/123')120+ expect(res).toBeNull()121+ })122+})123+124+describe('All', () => {125+ const node = new Node()126+ node.insert('ALL', '/all-methods', 'all methods') // ALL127+ it('/all-methods', () => {128+ res = node.search('get', '/all-methods')129+ expect(res).not.toBeNull()130+ expect(res.handler).toBe('all methods')131+ res = node.search('put', '/all-methods')132+ expect(res).not.toBeNull()133+ expect(res.handler).toBe('all methods')134+ })135+})added:test/router.test.js+88 added
1+const { Hono } = require('../src/hono')2+3+describe('Basic Usage', () => {4+ const router = new Hono()5+6+ it('get, post hello', async () => {7+ router.get('/hello', 'get hello')8+ router.post('/hello', 'post hello')9+10+ let res = await router.matchRoute('GET', '/hello')11+ expect(res).not.toBeNull()12+ expect(res.handler[0]).toBe('get hello')13+14+ res = await router.matchRoute('POST', '/hello')15+ expect(res).not.toBeNull()16+ expect(res.handler[0]).toBe('post hello')17+18+ res = await router.matchRoute('PUT', '/hello')19+ expect(res).toBeNull()20+21+ res = await router.matchRoute('GET', '/')22+ expect(res).toBeNull()23+ })24+})25+26+describe('Complex', () => {27+ let router = new Hono()28+29+ it('Named Param', async () => {30+ router.get('/entry/:id', 'get entry')31+ res = await router.matchRoute('GET', '/entry/123')32+ expect(res).not.toBeNull()33+ expect(res.handler[0]).toBe('get entry')34+ expect(res.params['id']).toBe('123')35+ })36+37+ it('Wildcard', async () => {38+ router.get('/wild/*/card', 'get wildcard')39+ res = await router.matchRoute('GET', '/wild/xxx/card')40+ expect(res).not.toBeNull()41+ expect(res.handler[0]).toBe('get wildcard')42+ })43+44+ it('Regexp', async () => {45+ router.get('/post/:date{[0-9]+}/:title{[a-z]+}', 'get post')46+ res = await router.matchRoute('GET', '/post/20210101/hello')47+ expect(res).not.toBeNull()48+ expect(res.handler[0]).toBe('get post')49+ expect(res.params['date']).toBe('20210101')50+ expect(res.params['title']).toBe('hello')51+ res = await router.matchRoute('GET', '/post/onetwothree')52+ expect(res).toBeNull()53+ res = await router.matchRoute('GET', '/post/123/123')54+ expect(res).toBeNull()55+ })56+})57+58+describe('Chained Route', () => {59+ let router = new Hono()60+61+ it('Return rooter object', async () => {62+ router = router.patch('/hello', 'patch hello')63+ expect(router).not.toBeNull()64+ router = router.delete('/hello', 'delete hello')65+ res = await router.matchRoute('DELETE', '/hello')66+ expect(res).not.toBeNull()67+ expect(res.handler[0]).toBe('delete hello')68+ })69+70+ it('Chain with route method', async () => {71+ router.route('/api/book').get('get book').post('post book').put('put book')72+73+ res = await router.matchRoute('GET', '/api/book')74+ expect(res).not.toBeNull()75+ expect(res.handler[0]).toBe('get book')76+77+ res = await router.matchRoute('POST', '/api/book')78+ expect(res).not.toBeNull()79+ expect(res.handler[0]).toBe('post book')80+81+ res = await router.matchRoute('PUT', '/api/book')82+ expect(res).not.toBeNull()83+ expect(res.handler[0]).toBe('put book')84+85+ res = await router.matchRoute('DELETE', '/api/book')86+ expect(res).toBeNull()87+ })88+})added:test/util.test.js+44 added
1+const { splitPath, getPattern, getPathFromURL } = require('../src/util')2+3+describe('Utility methods', () => {4+ it('splitPath', () => {5+ let ps = splitPath('/')6+ expect(ps[0]).toBe('')7+ ps = splitPath('/hello')8+ expect(ps[0]).toBe('hello')9+ ps = splitPath('*')10+ expect(ps[0]).toBe('*')11+ ps = splitPath('/wildcard-abc/*/wildcard-efg')12+ expect(ps[0]).toBe('wildcard-abc')13+ expect(ps[1]).toBe('*')14+ expect(ps[2]).toBe('wildcard-efg')15+ ps = splitPath('/map/:location/events')16+ expect(ps[0]).toBe('map')17+ expect(ps[1]).toBe(':location')18+ expect(ps[2]).toBe('events')19+ })20+21+ it('getPattern', () => {22+ let res = getPattern(':id')23+ expect(res[0]).toBe('id')24+ expect(res[1]).toBe('(.+)')25+ res = getPattern(':id{[0-9]+}')26+ expect(res[0]).toBe('id')27+ expect(res[1]).toBe('([0-9]+)')28+ })29+30+ it('getPathFromURL', () => {31+ let path = getPathFromURL('https://example.com/')32+ expect(path).toBe('/')33+ path = getPathFromURL('https://example.com/hello')34+ expect(path).toBe('/hello')35+ path = getPathFromURL('https://example.com/hello/hey')36+ expect(path).toBe('/hello/hey')37+ path = getPathFromURL('https://example.com/hello?name=foo')38+ expect(path).toBe('/hello')39+ path = getPathFromURL('https://example.com/hello/hey?name=foo&name=bar')40+ expect(path).toBe('/hello/hey')41+ path = getPathFromURL('https://example.com/hello/hey#fragment')42+ expect(path).toBe('/hello/hey')43+ })44+})