Skip to content
Myr

context.test.ts

This file

Path

src/context.test.ts

629 lines · 19.8 KiB · TypeScript

Last changed by

fix(types): allow returning a Blob as a response body (#5446)Yusuke Wadabefore adoption90d02fb

History of this file

Take 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.body() - Blob', async () => {133    const res = c.body(new Blob(['Hi']))134    expect(await res.text()).toBe('Hi')135  })136137  it('c.body() - File', async () => {138    const res = c.body(new File(['Hi'], 'greeting.txt'))139    expect(await res.text()).toBe('Hi')140  })141142  it('c.header()', async () => {143    c.header('X-Foo', 'Bar')144    const res = c.body('Hi')145    const foo = res.headers.get('X-Foo')146    expect(foo).toBe('Bar')147  })148149  it('c.header() - append', async () => {150    c.header('X-Foo', 'Bar')151    c.header('X-Foo', 'Buzz', { append: true })152    const res = c.body('Hi')153    const foo = res.headers.get('X-Foo')154    expect(foo).toBe('Bar, Buzz')155  })156157  it('c.set() and c.get() with symbol key', () => {158    const sym = Symbol('key')159    expect(c.get(sym)).toBe(undefined)160    c.set(sym, 'value')161    expect(c.get(sym)).toBe('value')162  })163164  it('c.set() and c.get()', async () => {165    expect(c.get('foo')).toBe(undefined)166    c.set('foo', 'bar')167    expect(c.get('foo')).toBe('bar')168    expect(c.get('foo2')).toBe(undefined)169  })170171  it('c.var', async () => {172    expect(c.var.foo).toBe(undefined)173    c.set('foo', 'bar')174    expect(c.var.foo).toBe('bar')175    expect(c.var.foo2).toBe(undefined)176  })177178  it('c.notFound()', async () => {179    const res = c.notFound()180    expect(res).instanceOf(Response)181  })182183  it('Should set headers if already this.#headers is created by `c.header()`', async () => {184    c.header('X-Foo', 'Bar')185    c.header('X-Foo', 'Buzz', { append: true })186    const res = c.body('Hi', {187      headers: {188        'X-Message': 'Hi',189      },190    })191    expect(res.headers.get('X-Foo')).toBe('Bar, Buzz')192    expect(res.headers.get('X-Message')).toBe('Hi')193  })194195  it('c.header() - append, c.html()', async () => {196    c.header('X-Foo', 'Bar', { append: true })197    const res = await c.html('<h1>This rendered fine</h1>')198    expect(res.headers.get('content-type')).toMatch(/^text\/html/)199  })200201  it('c.header() - clear the header', async () => {202    c.header('X-Foo', 'Bar')203    c.header('X-Foo', undefined)204    c.header('X-Foo2', 'Bar')205    const res = c.body('Hi')206    expect(res.headers.get('X-Foo')).toBe(null)207    c.header('X-Foo2', undefined)208    const res2 = c.body('Hi')209    expect(res2.headers.get('X-Foo2')).toBe(null)210  })211212  it('c.header() - clear the header when append is true', async () => {213    c.header('X-Foo', 'Bar', { append: true })214    c.header('X-Foo', undefined)215    expect(c.res.headers.get('X-Foo')).toBe(null)216  })217218  it('c.body() - multiple header', async () => {219    const res = c.body('Hi', 200, {220      'X-Foo': ['Bar', 'Buzz'],221    })222    const foo = res.headers.get('X-Foo')223    expect(foo).toBe('Bar, Buzz')224  })225226  it('c.body() - content-type cannot be overridden by the default response when append headers', async () => {227    c.header('Vary', 'Accept-Encoding', { append: true })228    c.res229    c.header('Content-Type', 'text/html')230    const res = c.body('<h1>Hi</h1>')231    expect(res.headers.get('Content-Type')).toMatch('text/html')232  })233234  it('c.body() - content-type can set explicitly via c.res.headers', async () => {235    c.header('Vary', 'Accept-Encoding', { append: true })236    c.res.headers.set('Content-Type', 'text/html')237    const res = c.body('<h1>Hi</h1>')238    expect(res.headers.get('Content-Type')).toMatch('text/html')239  })240241  it('c.body() - Different header settings require ensuring order', async () => {242    c.header('Vary', 'Accept-Encoding', { append: true })243    c.header('Content-Type', 'image/png')244    c.res.headers.set('Content-Type', 'text/html')245    const res = c.body('<h1>Hi</h1>')246    expect(res.headers.get('Content-Type')).toMatch('text/html')247  })248249  it('c.status()', async () => {250    c.status(201)251    const res = c.body('Hi')252    expect(res.status).toBe(201)253  })254255  it('Complex pattern', async () => {256    c.status(404)257    const res = c.json({ hono: 'great app' })258    expect(res.status).toBe(404)259    expect(res.headers.get('Content-Type')).toMatch('application/json')260    const obj: { [key: string]: string } = await res.json()261    expect(obj['hono']).toBe('great app')262  })263264  it('Has headers and status', async () => {265    c.header('x-custom1', 'Message1')266    c.header('x-custom2', 'Message2')267    c.status(200)268    const res = c.newResponse('this is body', 201, {269      'x-custom3': 'Message3',270      'x-custom2': 'Message2-Override',271    })272    expect(res.headers.get('x-Custom1')).toBe('Message1')273    expect(res.headers.get('x-Custom2')).toBe('Message2-Override')274    expect(res.headers.get('x-Custom3')).toBe('Message3')275    expect(res.status).toBe(201)276277    // res is already set.278    c.res = res279    c.header('X-Custom4', 'Message4')280    c.status(202)281    expect(c.res.headers.get('X-Custom4')).toBe('Message4')282    expect(c.res.status).toBe(201)283    expect(await res.text()).toBe('this is body')284  })285286  it('Inherit current status if not specified', async () => {287    c.status(201)288    const res = c.newResponse('this is body', {289      headers: {290        'x-custom3': 'Message3',291        'x-custom2': 'Message2-Override',292      },293    })294    expect(res.headers.get('x-Custom2')).toBe('Message2-Override')295    expect(res.headers.get('x-Custom3')).toBe('Message3')296    expect(res.status).toBe(201)297    expect(await res.text()).toBe('this is body')298  })299300  it('Should append the previous headers to new Response', () => {301    c.res.headers.set('x-Custom1', 'Message1')302    const res2 = new Response('foo2', {303      headers: {304        'Content-Type': 'application/json',305      },306    })307    res2.headers.set('x-Custom2', 'Message2')308    c.res = res2309    expect(c.res.headers.get('x-Custom1')).toBe('Message1')310    expect(c.res.headers.get('Content-Type')).toBe('application/json')311  })312313  it('Should return 200 response', async () => {314    const res = c.text('Text')315    expect(res.status).toBe(200)316  })317318  it('Should return 204 response', async () => {319    c.status(204)320    const res = c.body(null)321    expect(res.status).toBe(204)322    expect(await res.text()).toBe('')323  })324325  it('Should be able read env', async () => {326    const req = new Request('http://localhost/')327    const key = 'a-secret-key'328    const ctx = new Context(req, {329      env: {330        API_KEY: key,331      },332    })333    expect(ctx.env.API_KEY).toBe(key)334  })335336  it('set and set', async () => {337    const ctx = new Context(req)338    expect(ctx.get('k-foo')).toEqual(undefined)339    ctx.set('k-foo', 'v-foo')340    expect(ctx.get('k-foo')).toEqual('v-foo')341    expect(ctx.get('k-bar')).toEqual(undefined)342    ctx.set('k-bar', { k: 'v' })343    expect(ctx.get('k-bar')).toEqual({ k: 'v' })344  })345346  it('has res object by default', async () => {347    c = new Context(req)348    c.res.headers.append('foo', 'bar')349    const res = c.text('foo')350    expect(res.headers.get('foo')).not.toBeNull()351    expect(res.headers.get('foo')).toBe('bar')352  })353})354355describe('event and executionCtx', () => {356  const req = new Request('http://localhost/')357358  it('Should return the event if accessing c.event', () => {359    const respondWith = vi.fn()360    const c = new Context(req, {361      // @ts-expect-error the type is not correct362      executionCtx: {363        respondWith: respondWith,364      },365    })366    expect(() => c.event).not.toThrowError()367    c.event.respondWith(new Response())368    expect(respondWith).toHaveBeenCalled()369  })370371  it('Should throw an error if accessing c.event', () => {372    const c = new Context(req)373    expect(() => c.event).toThrowError()374  })375376  it('Should return the executionCtx if accessing c.executionCtx', () => {377    const pathThroughOnException = vi.fn()378    const waitUntil = vi.fn()379    const c = new Context(req, {380      executionCtx: {381        passThroughOnException: pathThroughOnException,382        waitUntil: waitUntil,383        props: {},384      },385      env: {},386    })387    expect(() => c.executionCtx).not.toThrowError()388    c.executionCtx.passThroughOnException()389    expect(pathThroughOnException).toHaveBeenCalled()390    const asyncFunc = async () => {}391    c.executionCtx.waitUntil(asyncFunc())392    expect(waitUntil).toHaveBeenCalled()393  })394395  it('Should throw an error if accessing c.executionCtx', () => {396    const c = new Context(req)397    expect(() => c.executionCtx).toThrowError()398  })399})400401describe('Context header', () => {402  const req = new Request('http://localhost/')403  let c: Context404  beforeEach(() => {405    c = new Context(req)406  })407408  it('Should return only one content-type value', async () => {409    c.header('Content-Type', 'foo')410    const res = await c.html('foo')411    expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')412  })413414  it('Should rewrite header values correctly', async () => {415    c.res = await c.html('foo')416    const res = c.text('foo')417    expect(res.headers.get('Content-Type')).toMatch(/^text\/plain/)418  })419420  it('Should set header values if the #this.headers is set and the arg is ResponseInit', async () => {421    c.header('foo', 'bar')422    const res = c.body('foo', {423      headers: {424        'Content-Type': 'text/plain',425      },426    })427    expect(res.headers.get('foo')).toBe('bar')428  })429430  it('Should set cookie headers when re-assigning Response to `c.res`', () => {431    const cookies = ['foo=bar; Path=/', 'foo2=bar2; Path=/']432    const res = new Response(null)433    res.headers.append('set-cookie', cookies[0])434    res.headers.append('set-cookie', cookies[1])435    c.res = res436    expect(c.res.headers.getSetCookie().length).toBe(2)437438    // Re-assign439    const newCookies = ['foo3=bar3; Path=/']440    const newResponse = new Response(null)441    newResponse.headers.append('set-cookie', newCookies[0])442    c.res = newResponse443    expect(c.res.headers.getSetCookie().length).toBe(cookies.length)444    expect(c.res.headers.getSetCookie()).toEqual(cookies)445  })446447  it('Should keep previous cookies in response headers', () => {448    c.res.headers.append('set-cookie', 'foo=bar; Path=/')449    setCookie(c, 'foo2', 'bar2', { path: '/' })450    const res = c.json({ message: 'Hello' })451    const cookies = res.headers.getSetCookie()452    expect(cookies.includes('foo=bar; Path=/')).toBe(true)453    expect(cookies.includes('foo2=bar2; Path=/')).toBe(true)454  })455456  it('Should set set-cookie header values if c.res is already defined', () => {457    c.res = new Response(null, {458      headers: [459        ['set-cookie', 'a'],460        ['set-cookie', 'b'],461        ['set-cookie', 'c'],462      ],463    })464    const res = c.text('Hi')465    expect(res.headers.get('set-cookie')).toBe('a, b, c')466  })467468  it('Should be able to overwrite a fetch response with a new response.', async () => {469    c.res = makeResponseHeaderImmutable(new Response('bar'))470    c.res = new Response('foo', {471      headers: {472        'X-Custom': 'Message',473      },474    })475    expect(await c.res.text()).toBe('foo')476    expect(c.res.headers.get('X-Custom')).toBe('Message')477  })478479  it('Should be able to overwrite a response with a fetch response.', async () => {480    c.res = new Response('foo', {481      headers: {482        'X-Custom': 'Message',483      },484    })485    c.res = makeResponseHeaderImmutable(new Response('bar'))486    expect(await c.res.text()).toBe('bar')487    expect(c.res.headers.get('X-Custom')).toBe('Message')488  })489490  it('Should be able to set headers if the context is finalized', async () => {491    c.res = makeResponseHeaderImmutable(new Response('bar'))492    expect(c.finalized).toBe(true)493    c.header('X-Custom', 'Message')494    expect(c.res.headers.get('X-Custom')).toBe('Message')495  })496497  it('Should handle headers with array values correctly', async () => {498    c.header('X-Array', 'value1')499    const res = c.json({ test: 'data' }, 200, {500      'X-Array': ['new1', 'new2'],501    })502    expect(res.headers.get('X-Array')).toBe('new1, new2')503  })504505  it('Should remove existing header when new value is empty array', async () => {506    c.header('X-Test', 'existing')507    const res = c.json({ test: 'data' }, 200, {508      'X-Test': [],509    })510    expect(res.headers.get('X-Test')).toBeNull()511  })512513  it('Should override the default Content-Type even if the header name casing differs', async () => {514    const res = c.json({ type: 'urn:example:error' }, 400, {515      'content-type': 'application/problem+json',516    })517    expect(res.headers.get('Content-Type')).toBe('application/problem+json')518  })519520  it('Should apply the last value when header names differ only in casing', async () => {521    const res = c.body('foo', 200, {522      'X-Custom': 'first',523      'x-custom': 'second',524    })525    expect(res.headers.get('X-Custom')).toBe('second')526  })527})528529describe('Pass a ResponseInit to respond methods', () => {530  const req = new Request('http://localhost/')531  let c: Context532  beforeEach(() => {533    c = new Context(req)534  })535536  it('c.json()', async () => {537    const originalResponse = new Response('Unauthorized', {538      headers: {539        'content-type': 'text/plain',540        'x-custom': 'custom message',541      },542      status: 401,543    })544    const res = c.json(545      {546        message: 'Unauthorized',547      },548      originalResponse549    )550    expect(res.status).toBe(401)551    expect(res.headers.get('content-type')).toMatch(/^application\/json/)552    expect(res.headers.get('x-custom')).toBe('custom message')553    expect(await res.json()).toEqual({554      message: 'Unauthorized',555    })556  })557558  it('c.body()', async () => {559    const originalResponse = new Response('<h1>Hello</h1>', {560      headers: {561        'content-type': 'text/html',562      },563    })564    const res = c.body('<h2>Hello</h2>', originalResponse)565    expect(res.headers.get('content-type')).toMatch(/^text\/html/)566    expect(await res.text()).toBe('<h2>Hello</h2>')567  })568569  it('c.body() should retain context cookies from context and original response', async () => {570    setCookie(c, 'context', '1')571    setCookie(c, 'context', '2')572573    const originalResponse = new Response('', {574      headers: {575        'set-cookie': 'response=1; Path=/',576      },577    })578    const res = c.body('', originalResponse)579    const cookies = res.headers.getSetCookie()580    expect(cookies.includes('context=1; Path=/')).toBe(true)581    expect(cookies.includes('context=2; Path=/')).toBe(true)582    expect(cookies.includes('response=1; Path=/')).toBe(true)583  })584585  it('c.text()', async () => {586    const originalResponse = new Response(JSON.stringify({ foo: 'bar' }))587    const res = c.text('foo', originalResponse)588    expect(res.headers.get('content-type')).toMatch(/^text\/plain/)589    expect(await res.text()).toBe('foo')590  })591592  it('c.html()', async () => {593    const originalResponse = new Response('foo')594    const res = await c.html('<h1>foo</h1>', originalResponse)595    expect(res.headers.get('content-type')).toMatch(/^text\/html/)596    expect(await res.text()).toBe('<h1>foo</h1>')597  })598})599600declare module './context' {601  interface ContextRenderer {602    (content: string | Promise<string>, head: { title: string }): Response | Promise<Response>603  }604}605606describe('c.render', () => {607  const req = new Request('http://localhost/')608  let c: Context609  beforeEach(() => {610    c = new Context(req)611  })612613  it('Should return a Response from the default renderer', async () => {614    c.header('foo', 'bar')615    const res = await c.render('<h1>content</h1>', { title: 'dummy ' })616    expect(res.headers.get('foo')).toBe('bar')617    expect(await res.text()).toBe('<h1>content</h1>')618  })619620  it('Should return a Response from the custom renderer', async () => {621    c.setRenderer((content, head) => {622      return c.html(`<html><head>${head.title}</head><body>${content}</body></html>`)623    })624    c.header('foo', 'bar')625    const res = await c.render('<h1>content</h1>', { title: 'title' })626    expect(res.headers.get('foo')).toBe('bar')627    expect(await res.text()).toBe('<html><head>title</head><body><h1>content</h1></body></html>')628  })629})