handler.test.ts
This file
Path
src/adapter/cloudflare-pages/handler.test.ts
286 lines · 9.1 KiB · TypeScript
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–286why, one step back1import { getCookie } from '../../helper/cookie'2import { Hono } from '../../hono'3import { HTTPException } from '../../http-exception'4import type { EventContext } from './handler'5import { handle, handleMiddleware, serveStatic } from './handler'67type Env = {8 Bindings: {9 TOKEN: string10 }11}1213function createEventContext(14 context: Partial<EventContext<Env['Bindings']>>15): EventContext<Env['Bindings']> {16 return {17 data: {},18 env: {19 ...context.env,20 ASSETS: { fetch: vi.fn(), ...context.env?.ASSETS },21 TOKEN: context.env?.TOKEN ?? 'HONOISHOT',22 },23 functionPath: '_worker.js',24 next: vi.fn(),25 params: {},26 passThroughOnException: vi.fn(),27 props: {},28 request: new Request('http://localhost/api/foo'),29 waitUntil: vi.fn(),30 ...context,31 }32}3334describe('Adapter for Cloudflare Pages', () => {35 it('Should return 200 response', async () => {36 const request = new Request('http://localhost/api/foo')37 const env = {38 ASSETS: { fetch },39 TOKEN: 'HONOISHOT',40 }41 const waitUntil = vi.fn()42 const passThroughOnException = vi.fn()43 const props = {}44 const eventContext = createEventContext({45 request,46 env,47 waitUntil,48 passThroughOnException,49 })50 const app = new Hono<Env>()51 const appFetchSpy = vi.spyOn(app, 'fetch')52 app.get('/api/foo', (c) => {53 return c.json({ TOKEN: c.env.TOKEN, requestURL: c.req.url })54 })55 const handler = handle(app)56 const res = await handler(eventContext)57 expect(appFetchSpy).toHaveBeenCalledWith(58 request,59 { ...env, eventContext },60 { waitUntil, passThroughOnException, props }61 )62 expect(res.status).toBe(200)63 expect(await res.json()).toEqual({64 TOKEN: 'HONOISHOT',65 requestURL: 'http://localhost/api/foo',66 })67 })6869 it('Should not use `basePath()` if path argument is not passed', async () => {70 const request = new Request('http://localhost/api/error')71 const eventContext = createEventContext({ request })72 const app = new Hono().basePath('/api')7374 app.onError((e) => {75 throw e76 })77 app.get('/error', () => {78 throw new Error('Custom Error')79 })8081 const handler = handle(app)82 // It does throw the error if app is NOT "subApp"83 expect(() => handler(eventContext)).toThrowError('Custom Error')84 })85})8687describe('Middleware adapter for Cloudflare Pages', () => {88 it('Should return the middleware response', async () => {89 const request = new Request('http://localhost/api/foo', {90 headers: {91 Cookie: 'my_cookie=1234',92 },93 })94 const next = vi.fn().mockResolvedValue(Response.json('From Cloudflare Pages'))95 const eventContext = createEventContext({ request, next })96 const handler = handleMiddleware(async (c, next) => {97 const cookie = getCookie(c, 'my_cookie')9899 await next()100101 return c.json({ cookie, response: await c.res.json() })102 })103104 const res = await handler(eventContext)105106 expect(next).toHaveBeenCalled()107108 expect(await res.json()).toEqual({109 cookie: '1234',110 response: 'From Cloudflare Pages',111 })112 })113114 it('Should return the middleware response when exceptions are handled', async () => {115 const request = new Request('http://localhost/api/foo')116 const handler = handleMiddleware(async (c, next) => {117 await next()118119 return c.json({ error: c.error?.message })120 })121122 const next = vi.fn().mockRejectedValue(new Error('Error from next()'))123 const eventContext = createEventContext({ request, next })124 const res = await handler(eventContext)125126 expect(next).toHaveBeenCalled()127128 expect(await res.json()).toEqual({129 error: 'Error from next()',130 })131 })132133 it('Should return the middleware response if next() is not called', async () => {134 const request = new Request('http://localhost/api/foo')135 const handler = handleMiddleware(async (c) => {136 return c.json({ response: 'Skip Cloudflare Pages' })137 })138139 const next = vi.fn()140 const eventContext = createEventContext({ request, next })141 const res = await handler(eventContext)142143 expect(next).not.toHaveBeenCalled()144145 expect(await res.json()).toEqual({146 response: 'Skip Cloudflare Pages',147 })148 })149150 it('Should return the Pages response if the middleware does not return a response', async () => {151 const request = new Request('http://localhost/api/foo')152 const handler = handleMiddleware((_c, next) => next())153154 const next = vi.fn().mockResolvedValue(Response.json('From Cloudflare Pages'))155 const eventContext = createEventContext({ request, next })156 const res = await handler(eventContext)157158 expect(next).toHaveBeenCalled()159160 expect(await res.json()).toEqual('From Cloudflare Pages')161 })162163 it('Should handle a HTTPException by returning error.getResponse()', async () => {164 const request = new Request('http://localhost/api/foo')165 const handler = handleMiddleware(() => {166 const res = new Response('Unauthorized', { status: 401 })167 throw new HTTPException(401, { res })168 })169170 const next = vi.fn()171 const eventContext = createEventContext({ request, next })172 const res = await handler(eventContext)173174 expect(next).not.toHaveBeenCalled()175176 expect(res.status).toBe(401)177 expect(await res.text()).toBe('Unauthorized')178 })179180 it('Should handle an HTTPException thrown by next()', async () => {181 const request = new Request('http://localhost/api/foo')182 const handler = handleMiddleware((_c, next) => next())183184 const next = vi185 .fn()186 .mockRejectedValue(new HTTPException(401, { res: Response.json('Unauthorized') }))187 const eventContext = createEventContext({ request, next })188 const res = await handler(eventContext)189190 expect(next).toHaveBeenCalled()191192 expect(await res.json()).toEqual('Unauthorized')193 })194195 it('Should handle an Error thrown by next()', async () => {196 const request = new Request('http://localhost/api/foo')197 const handler = handleMiddleware((_c, next) => next())198199 const next = vi.fn().mockRejectedValue(new Error('Error from next()'))200 const eventContext = createEventContext({ request, next })201 await expect(handler(eventContext)).rejects.toThrowError('Error from next()')202 expect(next).toHaveBeenCalled()203 })204205 it('Should handle a non-Error thrown by next()', async () => {206 const request = new Request('http://localhost/api/foo')207 const handler = handleMiddleware((_c, next) => next())208209 const next = vi.fn().mockRejectedValue('Error from next()')210 const eventContext = createEventContext({ request, next })211 await expect(handler(eventContext)).rejects.toThrowError('Error from next()')212 expect(next).toHaveBeenCalled()213 })214215 it('Should rethrow an Error', async () => {216 const request = new Request('http://localhost/api/foo')217 const handler = handleMiddleware(() => {218 throw new Error('Something went wrong')219 })220221 const next = vi.fn()222 const eventContext = createEventContext({ request, next })223 await expect(handler(eventContext)).rejects.toThrowError('Something went wrong')224 expect(next).not.toHaveBeenCalled()225 })226227 it('Should rethrow non-Error exceptions', async () => {228 const request = new Request('http://localhost/api/foo')229 const handler = handleMiddleware(() => Promise.reject('Something went wrong'))230 const next = vi.fn()231 const eventContext = createEventContext({ request, next })232 await expect(handler(eventContext)).rejects.toThrowError('Something went wrong')233 expect(next).not.toHaveBeenCalled()234 })235236 it('Should set the data in eventContext.data', async () => {237 const next = vi.fn()238 const eventContext = createEventContext({ next })239 const handler = handleMiddleware(async (c, next) => {240 c.env.eventContext.data.user = 'Joe'241 await next()242 })243 expect(eventContext.data.user).toBeUndefined()244 await handler(eventContext)245 expect(eventContext.data.user).toBe('Joe')246 })247})248249describe('serveStatic()', () => {250 it('Should pass the raw request to ASSETS.fetch', async () => {251 const assetsFetch = vi.fn().mockResolvedValue(new Response('foo.png'))252 const request = new Request('http://localhost/foo.png')253 const env = {254 ASSETS: { fetch: assetsFetch },255 TOKEN: 'HONOISHOT',256 }257258 const eventContext = createEventContext({ request, env })259 const app = new Hono<Env>()260 app.use(serveStatic())261 const handler = handle(app)262 const res = await handler(eventContext)263264 expect(assetsFetch).toHaveBeenCalledWith(request)265 expect(res.status).toBe(200)266 expect(await res.text()).toBe('foo.png')267 })268269 it('Should respond with 404 if ASSETS.fetch returns a 404 response', async () => {270 const assetsFetch = vi.fn().mockResolvedValue(new Response(null, { status: 404 }))271 const request = new Request('http://localhost/foo.png')272 const env = {273 ASSETS: { fetch: assetsFetch },274 TOKEN: 'HONOISHOT',275 }276277 const eventContext = createEventContext({ request, env })278 const app = new Hono<Env>()279 app.use(serveStatic())280 const handler = handle(app)281 const res = await handler(eventContext)282283 expect(assetsFetch).toHaveBeenCalledWith(request)284 expect(res.status).toBe(404)285 })286})