feat: add `request` method (#132)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add `request` method. It's useful for testing.
authored by Yusuke Wada · committed by GitHub · parent e36b054 · Browse files · 6 files·+76 added−72 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+76 added−72 removed
- tests:+41 added−66 removed
- other:+35 added−6 removed
Provenance
- Commit
5d5fe23- Tree
804e8dd- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
e36b054
6 files changed+76 added−72 removed
modified:docs/README.ja.md+12 added
79 unmodified lines80 - app.**notFound**(handler)81 - app.**onError**(err, handler)82 - app.**fire**()83 - app.**fetch**(request, env, event)84+- app.**request**(path, option)85 86 ## ルーティング87 88 ### 基本298 unmodified lines387 export default app388 */389 ```390 391+## request392+393+`request`はテストの時に役に立つメソッドです。394+395+```js396+test('GET /hello is ok', async () => {397+ const res = await app.request('http://localhost/hello')398+ expect(res.status).toBe(200)399+})400+```401+402 ## HonoでCloudflare Workersのアプリを作る403 404 [Wrangler](https://developers.cloudflare.com/workers/cli-wrangler/)もしくは[Miniflare](https://miniflare.dev)を使えば、ローカル環境での開発から、デプロイ・公開までが数行のコマンドで簡単にできます。405 125 unmodified linesmodified:src/context.test.ts+6 added
93 unmodified lines94959697989910010110210310493 unmodified lines expect(c.res.headers.get('X-Custom4')).toBe('Message4') expect(c.res.status).toBe(201) expect(c.res.statusText).toBe('OK') })
it('Default status code is 200', async () => { const res = c.text('Text') expect(res.status).toBe(200) expect(res.statusText).toBe('OK') })})modified:src/context.ts+2 added-2 removed
53 unmodified lines54 this._statusText = getStatusText(number)55 }56 57 newResponse(data: Data, init: ResponseInit = {}): Response {58- init.status = init.status || this._status59- init.statusText = init.statusText || this._statusText58+ init.status = init.status || this._status || 20059+ init.statusText = init.statusText || this._statusText || getStatusText(init.status)60 61 init.headers = { ...this._headers, ...init.headers }62 63 // Content-Length63 unmodified linesmodified:src/hono.test.ts+35 added-66 removed
15 unmodified lines16 return c.html('<h1>Hono!!!</h1>')17 })18 19 it('GET /hello is ok', async () => {20- const req = new Request('http://localhost/hello')21- const res = await app.dispatch(req)20+ const res = await app.request('http://localhost/hello')21 expect(res).not.toBeNull()22 expect(res.status).toBe(200)23 expect(res.statusText).toBe('Hono is OK')24 expect(await res.text()).toBe('hello')25 })26 27 it('GET /hell-with-shortcuts is ok', async () => {29- const req = new Request('http://localhost/hello-with-shortcuts')30- const res = await app.dispatch(req)28+ const res = await app.request('http://localhost/hello-with-shortcuts')29 expect(res).not.toBeNull()30 expect(res.status).toBe(201)31 expect(res.statusText).toBe('Created')32 expect(res.headers.get('X-Custom')).toBe('This is Hono')1 unmodified line34 expect(await res.text()).toBe('<h1>Hono!!!</h1>')35 })36 37 it('GET / is not found', async () => {40- const req = new Request('http://localhost/')41- const res = await app.dispatch(req)38+ const res = await app.request('http://localhost/')39 expect(res).not.toBeNull()40 expect(res.status).toBe(404)41+ expect(res.statusText).toBe('Not Found')42 })43 })44 45 describe('strict parameter', () => {4 unmodified lines50 return c.text('/hello')51 })52 53 it('/hello/ is not found', async () => {56- let req = new Request('http://localhost/hello')57- let res = await app.dispatch(req)54+ let res = await app.request('http://localhost/hello')55 expect(res).not.toBeNull()56 expect(res.status).toBe(200)60- req = new Request('http://localhost/hello/')61- res = await app.dispatch(req)57+ res = await app.request('http://localhost/hello/')58 expect(res).not.toBeNull()59 expect(res.status).toBe(404)60 })61 })5 unmodified lines67 return c.text('/hello/')68 })69 70 it('/hello is not found', async () => {75- let req = new Request('http://localhost/hello/')76- let res = await app.dispatch(req)71+ let res = await app.request('http://localhost/hello/')72 expect(res).not.toBeNull()73 expect(res.status).toBe(200)79- req = new Request('http://localhost/hello')80- res = await app.dispatch(req)74+ res = await app.request('http://localhost/hello')75 expect(res).not.toBeNull()76 expect(res.status).toBe(404)77 })78 })5 unmodified lines84 return c.text('/hello')85 })86 87 it('/hello and /hello/ are treated as the same', async () => {94- let req = new Request('http://localhost/hello')95- let res = await app.dispatch(req)88+ let res = await app.request('http://localhost/hello')89 expect(res).not.toBeNull()90 expect(res.status).toBe(200)98- req = new Request('http://localhost/hello/')99- res = await app.dispatch(req)91+ res = await app.request('http://localhost/hello/')92 expect(res).not.toBeNull()93 expect(res.status).toBe(200)94 })95 })5 unmodified lines101 it('Return it self', async () => {102 const appRes = app.get('/', () => new Response('get /'))103 expect(appRes).not.toBeUndefined()104 appRes.delete('/', () => new Response('delete /'))113- const req = new Request('http://localhost/', { method: 'DELETE' })114- const res = await appRes.dispatch(req)105+ const res = await appRes.request('http://localhost/', { method: 'DELETE' })106 expect(res).not.toBeNull()107 expect(res.status).toBe(200)108 expect(await res.text()).toBe('delete /')109 })9 unmodified lines119 const user = app.route('/user')120 user.get('/login', (c) => c.text('get /user/login'))121 user.post('/regist', (c) => c.text('post /user/regist'))122 132- let req = new Request('http://localhost/book', { method: 'GET' })133- let res = await app.dispatch(req)123+ let res = await app.request('http://localhost/book', { method: 'GET' })124 expect(res.status).toBe(200)125 expect(await res.text()).toBe('get /book')126 137- req = new Request('http://localhost/book/123', { method: 'GET' })138- res = await app.dispatch(req)127+ res = await app.request('http://localhost/book/123', { method: 'GET' })128 expect(res.status).toBe(200)129 expect(await res.text()).toBe('get /book/123')130 142- req = new Request('http://localhost/book', { method: 'POST' })143- res = await app.dispatch(req)131+ res = await app.request('http://localhost/book', { method: 'POST' })132 expect(res.status).toBe(200)133 expect(await res.text()).toBe('post /book')134 147- req = new Request('http://localhost/book/', { method: 'GET' })148- res = await app.dispatch(req)135+ res = await app.request('http://localhost/book/', { method: 'GET' })136 expect(res.status).toBe(404)137 151- req = new Request('http://localhost/user/login', { method: 'GET' })152- res = await app.dispatch(req)138+ res = await app.request('http://localhost/user/login', { method: 'GET' })139 expect(res.status).toBe(200)140 expect(await res.text()).toBe('get /user/login')141 156- req = new Request('http://localhost/user/regist', { method: 'POST' })157- res = await app.dispatch(req)142+ res = await app.request('http://localhost/user/regist', { method: 'POST' })143 expect(res.status).toBe(200)144 expect(await res.text()).toBe('post /user/regist')145 })146 })2 unmodified lines149 const app = new Hono()150 151 app.get('/entry/:id', (c) => {152 const id = c.req.param('id')168- return new Response(`id is ${id}`, {169- status: 200,170- })153+ return c.text(`id is ${id}`)154 })155 156 app.get('/search', (c) => {157 const name = c.req.query('name')175- return new Response(`name is ${name}`, {176- status: 200,177- })158+ return c.text(`name is ${name}`)159 })160 161 app.get('/add-header', (c) => {162 const bar = c.req.header('X-Foo')182- return new Response(`foo is ${bar}`, {183- status: 200,184- })163+ return c.text(`foo is ${bar}`)164 })165 166 it('param of /entry/:id is found', async () => {188- const req = new Request('http://localhost/entry/123')189- const res = await app.dispatch(req)167+ const res = await app.request('http://localhost/entry/123')168 expect(res.status).toBe(200)169 expect(await res.text()).toBe('id is 123')170 })171 172 it('query of /search?name=sam is found', async () => {195- const req = new Request('http://localhost/search?name=sam')196- const res = await app.dispatch(req)173+ const res = await app.request('http://localhost/search?name=sam')174 expect(res.status).toBe(200)175 expect(await res.text()).toBe('name is sam')176 })177 178 it('/add-header header - X-Foo is Bar', async () => {179 const req = new Request('http://localhost/add-header')180 req.headers.append('X-Foo', 'Bar')204- const res = await app.dispatch(req)181+ const res = await app.request(req)182 expect(res.status).toBe(200)183 expect(await res.text()).toBe('foo is Bar')184 })185 })22 unmodified lines208 await next()209 c.res.headers.append('x-message-2', 'custom-header-2')210 })211 235- app.get('/hello', () => {236- return new Response('hello')212+ app.get('/hello', (c) => {213+ return c.text('hello')214 })215 app.get('/hello/:message', (c) => {216 const message = c.req.param('message')240- return new Response(`${message}`)217+ return c.text(`${message}`)218 })219 220 it('logging and custom header', async () => {244- const req = new Request('http://localhost/hello')245- const res = await app.dispatch(req)221+ const res = await app.request('http://localhost/hello')222 expect(res.status).toBe(200)223 expect(await res.text()).toBe('hello')224 expect(res.headers.get('x-custom')).toBe('root')225 expect(res.headers.get('x-message')).toBe('custom-header')226 expect(res.headers.get('x-message-2')).toBe('custom-header-2')227 })228 229 it('logging and custom header with named param', async () => {254- const req = new Request('http://localhost/hello/message')255- const res = await app.dispatch(req)230+ const res = await app.request('http://localhost/hello/message')231 expect(res.status).toBe(200)232 expect(await res.text()).toBe('message')233 expect(res.headers.get('x-custom')).toBe('root')234 expect(res.headers.get('x-message-2')).toBe('custom-header-2')15 unmodified lines250 return c.notFound()251 })252 253 it('Custom 404 Not Found', async () => {279- let req = new Request('http://localhost/hello')280- let res = await app.dispatch(req)254+ let res = await app.request('http://localhost/hello')255 expect(res.status).toBe(200)282- req = new Request('http://localhost/notfound')283- res = await app.dispatch(req)256+ res = await app.request('http://localhost/notfound')257 expect(res.status).toBe(404)285- req = new Request('http://localhost/foo')286- res = await app.dispatch(req)258+ res = await app.request('http://localhost/foo')259 expect(res.status).toBe(404)260 expect(await res.text()).toBe('Custom 404 Not Found')261 })262 })4 unmodified lines267 return c.redirect('/')268 })269 270 it('Absolute URL', async () => {299- const req = new Request('https://example.com/redirect')300- const res = await app.dispatch(req)271+ const res = await app.request('https://example.com/redirect')272 expect(res.status).toBe(302)273 expect(res.headers.get('Location')).toBe('https://example.com/')274 })275 })14 unmodified lines290 return c.text('Custom Error Message', 500)291 })292 293 it('Custom Error Message', async () => {323- let req = new Request('https://example.com/error')324- let res = await app.dispatch(req)294+ let res = await app.request('https://example.com/error')295 expect(res.status).toBe(500)296 expect(await res.text()).toBe('Custom Error Message')297 expect(res.headers.get('x-debug')).toBe('This is Error')298 329- req = new Request('https://example.com/error-middleware')330- res = await app.dispatch(req)299+ res = await app.request('https://example.com/error-middleware')300 expect(res.status).toBe(500)301 expect(await res.text()).toBe('Custom Error Message')302 expect(res.headers.get('x-debug')).toBe('This is Middleware Error')303 })26 unmodified lines330 const url = new URL('http://localhost/bar')331 url.searchParams.append('foo', 'bar')332 const req = new Request(url.toString())333 req.headers.append('User-Agent', 'bar')365- const res = await app.dispatch(req)334+ const res = await app.request(req)335 336 expect(res.status).toBe(200)337 expect(res.headers.get('X-Query')).toBe('bar')338 expect(res.headers.get('X-Param')).toBe('bar')7 unmodified linesmodified:src/hono.ts+9 added-4 removed
50 unmodified lines51 this.middlewareRouters = []52 this.tempPath = null53 }54 55- notFoundHandler: NotFoundHandler = (c: Context) => {55+ private notFoundHandler: NotFoundHandler = (c: Context) => {56 const message = '404 Not Found'57 return c.text(message, 404)58 }59 60- errorHandler: ErrorHandler = (err: Error, c: Context) => {60+ private errorHandler: ErrorHandler = (err: Error, c: Context) => {61 console.error(`${err.message}`)62 const message = 'Internal Server Error'63 return c.text(message, 500)64 }66 unmodified lines131 return this132 }133 134 // addRoute('get', '/', handler)135- addRoute(method: string, path: string, handler: Handler): Hono {135+ private addRoute(method: string, path: string, handler: Handler): Hono {136 method = method.toUpperCase()137 if (this.tempPath) {138 path = mergePath(this.tempPath, path)139 }140 this.router.add(method, path, handler)141 return this142 }143 144- async matchRoute(method: string, path: string): Promise<Result<Handler>> {144+ private async matchRoute(method: string, path: string): Promise<Result<Handler>> {145 return this.router.match(method, path)146 }147 148 async dispatch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {54 unmodified lines203 async fetch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {204 return this.dispatch(request, env, event)205 }206 207+ request(input: RequestInfo, requestInit?: RequestInit) {208+ const req = new Request(input, requestInit)209+ return this.dispatch(req)210+ }211+212 fire() {213 addEventListener('fetch', (event: FetchEvent): void => {214 event.respondWith(this.handleEvent(event))215 })2 unmodified linesmodified:README.md+12 added
79 unmodified lines80 - app.**notFound**(handler)81 - app.**onError**(err, handler)82 - app.**fire**()83 - app.**fetch**(request, env, event)84+- app.**request**(path, option)85 86 ## Routing87 88 ### Basic298 unmodified lines387 export default app388 */389 ```390 391+## request392+393+`request` is a useful method for testing.394+395+```js396+test('GET /hello is ok', async () => {397+ const res = await app.request('http://localhost/hello')398+ expect(res.status).toBe(200)399+})400+```401+402 ## Cloudflare Workers with Hono403 404 Using [Wrangler](https://developers.cloudflare.com/workers/cli-wrangler/) or [Miniflare](https://miniflare.dev), you can develop the application locally and publish it with few commands.405 122 unmodified lines