diff --git a/src/middleware/serve-static/index.test.ts b/src/middleware/serve-static/index.test.ts index 5d996aa1b..ca611b67b 100644 --- a/src/middleware/serve-static/index.test.ts +++ b/src/middleware/serve-static/index.test.ts @@ -3,14 +3,15 @@ import { serveStatic as baseServeStatic } from '.' describe('Serve Static Middleware', () => { const app = new Hono() + const getContent = vi.fn(async (path) => { + if (path.endsWith('not-found.txt')) { + return null + } + return `Hello in ${path}` + }) const serveStatic = baseServeStatic({ - getContent: async (path) => { - if (path.endsWith('not-found.txt')) { - return null - } - return `Hello in ${path}` - }, + getContent, pathResolve: (path) => { return `./${path}` }, @@ -18,6 +19,10 @@ describe('Serve Static Middleware', () => { app.get('/static/*', serveStatic) + beforeEach(() => { + getContent.mockClear() + }) + it('Should return 200 response - /static/hello.html', async () => { const res = await app.request('/static/hello.html') expect(res.status).toBe(200) @@ -42,6 +47,7 @@ describe('Serve Static Middleware', () => { const res = await app.request('/static/not-found.txt') expect(res.status).toBe(404) expect(await res.text()).toBe('404 Not Found') + expect(getContent).toBeCalledTimes(1) }) it('Should not allow a directory traversal - /static/%2e%2e/static/hello.html', async () => { diff --git a/src/middleware/serve-static/index.ts b/src/middleware/serve-static/index.ts index a0c97dea6..134f4c444 100644 --- a/src/middleware/serve-static/index.ts +++ b/src/middleware/serve-static/index.ts @@ -64,9 +64,12 @@ export const serveStatic = ( return await next() } pathWithOutDefaultDocument = pathResolve(pathWithOutDefaultDocument) - content = await getContent(pathWithOutDefaultDocument, c) - if (content) { - path = pathWithOutDefaultDocument + + if (pathWithOutDefaultDocument !== path) { + content = await getContent(pathWithOutDefaultDocument, c) + if (content) { + path = pathWithOutDefaultDocument + } } }