NuxtN
Nuxt11mo ago
9 replies
tim

How to test Nuxt 3 Nitro Server endpoints and middlewares (avoiding defineEventHandler not defined)

Hi, how would you test a Nuxt server api endpoint or middleware? I do struggle with ReferenceError: defineEventHandler is not defined errors. defineEventHandler is a Nitro-specific runtime utility that is not available in my test environment. The way my test is currently set up, I am trying to execute the middleware file directly, but defineEventHandler is not properly mocked. How could I do that? I haven't found any working online resources for examples of testing Nuxt server routes / Nitro routes with Vitest in a Nuxt project :/

Would be very happy if anyone could look into my setup or provide me with resources so that I can get my setup to work


 FAIL  ../tests/unit/server/middleware/visibilityGuard.global.spec.ts [ ../tests/unit/server/middleware/visibilityGuard.global.spec.ts ]
ReferenceError: defineEventHandler is not defined
 ❯ ../server/middleware/visibilityGuard.global.ts:5:1
      3| import { sendRedirect } from 'h3';
      4|
      5| export default defineEventHandler((event: H3Event<EventHandlerRequest>) => {
       | ^
      6|     const runtimeConfig: NitroRuntimeConfig = useRuntimeConfig(event);
      7|     const appState: string = runtimeConfig.APP_STATE || 'maintenance';
 ❯ ../tests/unit/server/middleware/visibilityGuard.global.spec.ts:6:1
Was this page helpful?