context.test.ts
This file
Path
src/context.test.ts
597 lines · 18.8 KiB · TypeScript
Last changed by
Not known.
History of this fileTake it
1import { Context } from './context'2import { setCookie } from './helper/cookie'34const makeResponseHeaderImmutable = (res: Response) => {5 Object.defineProperty(res, 'headers', {6 value: new Proxy(res.headers, {7 set(target, prop, value) {8 if (prop === 'set') {9 throw new TypeError('Cannot modify headers: Headers are immutable')10 }11 return Reflect.set(target, prop, value)12 },13 get(target, prop, receiver) {14 if (prop === 'set') {15 return function () {16 throw new TypeError('Cannot modify headers: Headers are immutable')17 }18 }19 const value = Reflect.get(target, prop)20 if (typeof value === 'function') {21 return Object.defineProperties(22 function (...args: unknown[]) {23 // @ts-expect-error: `this` context is intentionally dynamic for proxy method binding24 return Reflect.apply(value, this === receiver ? target : this, args)25 },26 {27 name: { value: value.name },28 length: { value: value.length },29 }30 )31 }32 return value33 },34 }),35 writable: false,36 })37 return res38}3940describe('Context', () => {41 const req = new Request('http://localhost/')4243 let c: Context44 beforeEach(() => {45 c = new Context(req)46 })4748 it('c.text()', async () => {49 const res = c.text('text in c', 201, { 'X-Custom': 'Message' })50 expect(res.status).toBe(201)51 expect(res.headers.get('Content-Type')).toMatch(/^text\/plain/)52 expect(await res.text()).toBe('text in c')53 expect(res.headers.get('X-Custom')).toBe('Message')54 })5556 it('c.text() with c.status()', async () => {57 c.status(404)58 const res = c.text('not found')59 expect(res.status).toBe(404)60 expect(res.headers.get('Content-Type')).toMatch(/^text\/plain/)61 expect(await res.text()).toBe('not found')62 })6364 it('c.json()', async () => {65 const res = c.json({ message: 'Hello' }, 201, { 'X-Custom': 'Message' })66 expect(res.status).toBe(201)67 expect(res.headers.get('Content-Type')).toMatch('application/json')68 const text = await res.text()69 expect(text).toBe('{"message":"Hello"}')70 expect(res.headers.get('X-Custom')).toBe('Message')71 })7273 it('c.html()', async () => {74 const res: Response = c.html('<h1>Hello! Hono!</h1>', 201, { 'X-Custom': 'Message' })75 expect(res.status).toBe(201)76 expect(res.headers.get('Content-Type')).toMatch('text/html')77 expect(await res.text()).toBe('<h1>Hello! Hono!</h1>')78 expect(res.headers.get('X-Custom')).toBe('Message')79 })8081 it('c.html() with async', async () => {82 const resPromise: Promise<Response> = c.html(83 new Promise<string>((resolve) => setTimeout(() => resolve('<h1>Hello! Hono!</h1>'), 0)),84 201,85 {86 'X-Custom': 'Message',87 }88 )89 const res = await resPromise90 expect(res.status).toBe(201)91 expect(res.headers.get('Content-Type')).toMatch('text/html')92 expect(await res.text()).toBe('<h1>Hello! Hono!</h1>')93 expect(res.headers.get('X-Custom')).toBe('Message')94 })9596 it('c.redirect()', async () => {97 let res = c.redirect('/destination')98 expect(res.status).toBe(302)99 expect(res.headers.get('Location')).toBe('/destination')100 res = c.redirect('https://example.com/destination')101 expect(res.status).toBe(302)102 expect(res.headers.get('Location')).toBe('https://example.com/destination')103 })104105 it('c.redirect() w/ URL', async () => {106 const res = c.redirect(new URL('/destination', 'https://example.com'))107 expect(res.status).toBe(302)108 expect(res.headers.get('Location')).toBe('https://example.com/destination')109 })110111 it('c.redirect() w/ multibytes', async () => {112 const res = c.redirect('https://example.com/こんにちは')113 expect(res.headers.get('Location')).toBe(114 'https://example.com/%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF'115 )116 })117118 const unchangedURLString = [119 'https://example.com/%hello', // invalid ASCII chars120 'https://example.com/%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF?abc',121 'https://localhost/api?redirect_uri=https%3A%2F%2Fexample.com', // with ://122 'https://localhost/api?redirect_uri=https%3A%2F%2Fexample.com&scope=email%20profile', // with spaces and ://123 ]124125 unchangedURLString.forEach((urlString) => {126 it(`c.redirect() w/ ${urlString}`, () => {127 const res = c.redirect(urlString)128 expect(res.headers.get('Location')).toBe(urlString)129 })130 })131132 it('c.header()', async () => {133 c.header('X-Foo', 'Bar')134 const res = c.body('Hi')135 const foo = res.headers.get('X-Foo')136 expect(foo).toBe('Bar')137 })138139 it('c.header() - append', async () => {140 c.header('X-Foo', 'Bar')141 c.header('X-Foo', 'Buzz', { append: true })142 const res = c.body('Hi')143 const foo = res.headers.get('X-Foo')144 expect(foo).toBe('Bar, Buzz')145 })146147 it('c.set() and c.get()', async () => {148 expect(c.get('foo')).toBe(undefined)149 c.set('foo', 'bar')150 expect(c.get('foo')).toBe('bar')151 expect(c.get('foo2')).toBe(undefined)152 })153154 it('c.var', async () => {155 expect(c.var.foo).toBe(undefined)156 c.set('foo', 'bar')157 expect(c.var.foo).toBe('bar')158 expect(c.var.foo2).toBe(undefined)159 })160161 it('c.notFound()', async () => {162 const res = c.notFound()163 expect(res).instanceOf(Response)164 })165166 it('Should set headers if already this.#headers is created by `c.header()`', async () => {167 c.header('X-Foo', 'Bar')168 c.header('X-Foo', 'Buzz', { append: true })169 const res = c.body('Hi', {170 headers: {171 'X-Message': 'Hi',172 },173 })174 expect(res.headers.get('X-Foo')).toBe('Bar, Buzz')175 expect(res.headers.get('X-Message')).toBe('Hi')176 })177178 it('c.header() - append, c.html()', async () => {179 c.header('X-Foo', 'Bar', { append: true })180 const res = await c.html('<h1>This rendered fine</h1>')181 expect(res.headers.get('content-type')).toMatch(/^text\/html/)182 })183184 it('c.header() - clear the header', async () => {185 c.header('X-Foo', 'Bar')186 c.header('X-Foo', undefined)187 c.header('X-Foo2', 'Bar')188 const res = c.body('Hi')189 expect(res.headers.get('X-Foo')).toBe(null)190 c.header('X-Foo2', undefined)191 const res2 = c.body('Hi')192 expect(res2.headers.get('X-Foo2')).toBe(null)193 })194195 it('c.header() - clear the header when append is true', async () => {196 c.header('X-Foo', 'Bar', { append: true })197 c.header('X-Foo', undefined)198 expect(c.res.headers.get('X-Foo')).toBe(null)199 })200201 it('c.body() - multiple header', async () => {202 const res = c.body('Hi', 200, {203 'X-Foo': ['Bar', 'Buzz'],204 })205 const foo = res.headers.get('X-Foo')206 expect(foo).toBe('Bar, Buzz')207 })208209 it('c.body() - content-type cannot be overridden by the default response when append headers', async () => {210 c.header('Vary', 'Accept-Encoding', { append: true })211 c.res212 c.header('Content-Type', 'text/html')213 const res = c.body('<h1>Hi</h1>')214 expect(res.headers.get('Content-Type')).toMatch('text/html')215 })216217 it('c.body() - content-type can set explicitly via c.res.headers', async () => {218 c.header('Vary', 'Accept-Encoding', { append: true })219 c.res.headers.set('Content-Type', 'text/html')220 const res = c.body('<h1>Hi</h1>')221 expect(res.headers.get('Content-Type')).toMatch('text/html')222 })223224 it('c.body() - Different header settings require ensuring order', async () => {225 c.header('Vary', 'Accept-Encoding', { append: true })226 c.header('Content-Type', 'image/png')227 c.res.headers.set('Content-Type', 'text/html')228 const res = c.body('<h1>Hi</h1>')229 expect(res.headers.get('Content-Type')).toMatch('text/html')230 })231232 it('c.status()', async () => {233 c.status(201)234 const res = c.body('Hi')235 expect(res.status).toBe(201)236 })237238 it('Complex pattern', async () => {239 c.status(404)240 const res = c.json({ hono: 'great app' })241 expect(res.status).toBe(404)242 expect(res.headers.get('Content-Type')).toMatch('application/json')243 const obj: { [key: string]: string } = await res.json()244 expect(obj['hono']).toBe('great app')245 })246247 it('Has headers and status', async () => {248 c.header('x-custom1', 'Message1')249 c.header('x-custom2', 'Message2')250 c.status(200)251 const res = c.newResponse('this is body', 201, {252 'x-custom3': 'Message3',253 'x-custom2': 'Message2-Override',254 })255 expect(res.headers.get('x-Custom1')).toBe('Message1')256 expect(res.headers.get('x-Custom2')).toBe('Message2-Override')257 expect(res.headers.get('x-Custom3')).toBe('Message3')258 expect(res.status).toBe(201)259260 // res is already set.261 c.res = res262 c.header('X-Custom4', 'Message4')263 c.status(202)264 expect(c.res.headers.get('X-Custom4')).toBe('Message4')265 expect(c.res.status).toBe(201)266 expect(await res.text()).toBe('this is body')267 })268269 it('Inherit current status if not specified', async () => {270 c.status(201)271 const res = c.newResponse('this is body', {272 headers: {273 'x-custom3': 'Message3',274 'x-custom2': 'Message2-Override',275 },276 })277 expect(res.headers.get('x-Custom2')).toBe('Message2-Override')278 expect(res.headers.get('x-Custom3')).toBe('Message3')279 expect(res.status).toBe(201)280 expect(await res.text()).toBe('this is body')281 })282283 it('Should append the previous headers to new Response', () => {284 c.res.headers.set('x-Custom1', 'Message1')285 const res2 = new Response('foo2', {286 headers: {287 'Content-Type': 'application/json',288 },289 })290 res2.headers.set('x-Custom2', 'Message2')291 c.res = res2292 expect(c.res.headers.get('x-Custom1')).toBe('Message1')293 expect(c.res.headers.get('Content-Type')).toBe('application/json')294 })295296 it('Should return 200 response', async () => {297 const res = c.text('Text')298 expect(res.status).toBe(200)299 })300301 it('Should return 204 response', async () => {302 c.status(204)303 const res = c.body(null)304 expect(res.status).toBe(204)305 expect(await res.text()).toBe('')306 })307308 it('Should be able read env', async () => {309 const req = new Request('http://localhost/')310 const key = 'a-secret-key'311 const ctx = new Context(req, {312 env: {313 API_KEY: key,314 },315 })316 expect(ctx.env.API_KEY).toBe(key)317 })318319 it('set and set', async () => {320 const ctx = new Context(req)321 expect(ctx.get('k-foo')).toEqual(undefined)322 ctx.set('k-foo', 'v-foo')323 expect(ctx.get('k-foo')).toEqual('v-foo')324 expect(ctx.get('k-bar')).toEqual(undefined)325 ctx.set('k-bar', { k: 'v' })326 expect(ctx.get('k-bar')).toEqual({ k: 'v' })327 })328329 it('has res object by default', async () => {330 c = new Context(req)331 c.res.headers.append('foo', 'bar')332 const res = c.text('foo')333 expect(res.headers.get('foo')).not.toBeNull()334 expect(res.headers.get('foo')).toBe('bar')335 })336})337338describe('event and executionCtx', () => {339 const req = new Request('http://localhost/')340341 it('Should return the event if accessing c.event', () => {342 const respondWith = vi.fn()343 const c = new Context(req, {344 // @ts-expect-error the type is not correct345 executionCtx: {346 respondWith: respondWith,347 },348 })349 expect(() => c.event).not.toThrowError()350 c.event.respondWith(new Response())351 expect(respondWith).toHaveBeenCalled()352 })353354 it('Should throw an error if accessing c.event', () => {355 const c = new Context(req)356 expect(() => c.event).toThrowError()357 })358359 it('Should return the executionCtx if accessing c.executionCtx', () => {360 const pathThroughOnException = vi.fn()361 const waitUntil = vi.fn()362 const c = new Context(req, {363 executionCtx: {364 passThroughOnException: pathThroughOnException,365 waitUntil: waitUntil,366 props: {},367 },368 env: {},369 })370 expect(() => c.executionCtx).not.toThrowError()371 c.executionCtx.passThroughOnException()372 expect(pathThroughOnException).toHaveBeenCalled()373 const asyncFunc = async () => {}374 c.executionCtx.waitUntil(asyncFunc())375 expect(waitUntil).toHaveBeenCalled()376 })377378 it('Should throw an error if accessing c.executionCtx', () => {379 const c = new Context(req)380 expect(() => c.executionCtx).toThrowError()381 })382})383384describe('Context header', () => {385 const req = new Request('http://localhost/')386 let c: Context387 beforeEach(() => {388 c = new Context(req)389 })390391 it('Should return only one content-type value', async () => {392 c.header('Content-Type', 'foo')393 const res = await c.html('foo')394 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')395 })396397 it('Should rewrite header values correctly', async () => {398 c.res = await c.html('foo')399 const res = c.text('foo')400 expect(res.headers.get('Content-Type')).toMatch(/^text\/plain/)401 })402403 it('Should set header values if the #this.headers is set and the arg is ResponseInit', async () => {404 c.header('foo', 'bar')405 const res = c.body('foo', {406 headers: {407 'Content-Type': 'text/plain',408 },409 })410 expect(res.headers.get('foo')).toBe('bar')411 })412413 it('Should set cookie headers when re-assigning Response to `c.res`', () => {414 const cookies = ['foo=bar; Path=/', 'foo2=bar2; Path=/']415 const res = new Response(null)416 res.headers.append('set-cookie', cookies[0])417 res.headers.append('set-cookie', cookies[1])418 c.res = res419 expect(c.res.headers.getSetCookie().length).toBe(2)420421 // Re-assign422 const newCookies = ['foo3=bar3; Path=/']423 const newResponse = new Response(null)424 newResponse.headers.append('set-cookie', newCookies[0])425 c.res = newResponse426 expect(c.res.headers.getSetCookie().length).toBe(cookies.length)427 expect(c.res.headers.getSetCookie()).toEqual(cookies)428 })429430 it('Should keep previous cookies in response headers', () => {431 c.res.headers.append('set-cookie', 'foo=bar; Path=/')432 setCookie(c, 'foo2', 'bar2', { path: '/' })433 const res = c.json({ message: 'Hello' })434 const cookies = res.headers.getSetCookie()435 expect(cookies.includes('foo=bar; Path=/')).toBe(true)436 expect(cookies.includes('foo2=bar2; Path=/')).toBe(true)437 })438439 it('Should set set-cookie header values if c.res is already defined', () => {440 c.res = new Response(null, {441 headers: [442 ['set-cookie', 'a'],443 ['set-cookie', 'b'],444 ['set-cookie', 'c'],445 ],446 })447 const res = c.text('Hi')448 expect(res.headers.get('set-cookie')).toBe('a, b, c')449 })450451 it('Should be able to overwrite a fetch response with a new response.', async () => {452 c.res = makeResponseHeaderImmutable(new Response('bar'))453 c.res = new Response('foo', {454 headers: {455 'X-Custom': 'Message',456 },457 })458 expect(await c.res.text()).toBe('foo')459 expect(c.res.headers.get('X-Custom')).toBe('Message')460 })461462 it('Should be able to overwrite a response with a fetch response.', async () => {463 c.res = new Response('foo', {464 headers: {465 'X-Custom': 'Message',466 },467 })468 c.res = makeResponseHeaderImmutable(new Response('bar'))469 expect(await c.res.text()).toBe('bar')470 expect(c.res.headers.get('X-Custom')).toBe('Message')471 })472473 it('Should be able to set headers if the context is finalized', async () => {474 c.res = makeResponseHeaderImmutable(new Response('bar'))475 expect(c.finalized).toBe(true)476 c.header('X-Custom', 'Message')477 expect(c.res.headers.get('X-Custom')).toBe('Message')478 })479480 it('Should handle headers with array values correctly', async () => {481 c.header('X-Array', 'value1')482 const res = c.json({ test: 'data' }, 200, {483 'X-Array': ['new1', 'new2'],484 })485 expect(res.headers.get('X-Array')).toBe('new1, new2')486 })487488 it('Should remove existing header when new value is empty array', async () => {489 c.header('X-Test', 'existing')490 const res = c.json({ test: 'data' }, 200, {491 'X-Test': [],492 })493 expect(res.headers.get('X-Test')).toBeNull()494 })495})496497describe('Pass a ResponseInit to respond methods', () => {498 const req = new Request('http://localhost/')499 let c: Context500 beforeEach(() => {501 c = new Context(req)502 })503504 it('c.json()', async () => {505 const originalResponse = new Response('Unauthorized', {506 headers: {507 'content-type': 'text/plain',508 'x-custom': 'custom message',509 },510 status: 401,511 })512 const res = c.json(513 {514 message: 'Unauthorized',515 },516 originalResponse517 )518 expect(res.status).toBe(401)519 expect(res.headers.get('content-type')).toMatch(/^application\/json/)520 expect(res.headers.get('x-custom')).toBe('custom message')521 expect(await res.json()).toEqual({522 message: 'Unauthorized',523 })524 })525526 it('c.body()', async () => {527 const originalResponse = new Response('<h1>Hello</h1>', {528 headers: {529 'content-type': 'text/html',530 },531 })532 const res = c.body('<h2>Hello</h2>', originalResponse)533 expect(res.headers.get('content-type')).toMatch(/^text\/html/)534 expect(await res.text()).toBe('<h2>Hello</h2>')535 })536537 it('c.body() should retain context cookies from context and original response', async () => {538 setCookie(c, 'context', '1')539 setCookie(c, 'context', '2')540541 const originalResponse = new Response('', {542 headers: {543 'set-cookie': 'response=1; Path=/',544 },545 })546 const res = c.body('', originalResponse)547 const cookies = res.headers.getSetCookie()548 expect(cookies.includes('context=1; Path=/')).toBe(true)549 expect(cookies.includes('context=2; Path=/')).toBe(true)550 expect(cookies.includes('response=1; Path=/')).toBe(true)551 })552553 it('c.text()', async () => {554 const originalResponse = new Response(JSON.stringify({ foo: 'bar' }))555 const res = c.text('foo', originalResponse)556 expect(res.headers.get('content-type')).toMatch(/^text\/plain/)557 expect(await res.text()).toBe('foo')558 })559560 it('c.html()', async () => {561 const originalResponse = new Response('foo')562 const res = await c.html('<h1>foo</h1>', originalResponse)563 expect(res.headers.get('content-type')).toMatch(/^text\/html/)564 expect(await res.text()).toBe('<h1>foo</h1>')565 })566})567568declare module './context' {569 interface ContextRenderer {570 (content: string | Promise<string>, head: { title: string }): Response | Promise<Response>571 }572}573574describe('c.render', () => {575 const req = new Request('http://localhost/')576 let c: Context577 beforeEach(() => {578 c = new Context(req)579 })580581 it('Should return a Response from the default renderer', async () => {582 c.header('foo', 'bar')583 const res = await c.render('<h1>content</h1>', { title: 'dummy ' })584 expect(res.headers.get('foo')).toBe('bar')585 expect(await res.text()).toBe('<h1>content</h1>')586 })587588 it('Should return a Response from the custom renderer', async () => {589 c.setRenderer((content, head) => {590 return c.html(`<html><head>${head.title}</head><body>${content}</body></html>`)591 })592 c.header('foo', 'bar')593 const res = await c.render('<h1>content</h1>', { title: 'title' })594 expect(res.headers.get('foo')).toBe('bar')595 expect(await res.text()).toBe('<html><head>title</head><body><h1>content</h1></body></html>')596 })597})