NuxtN
Nuxt5mo ago
5 replies
AxelSorensen

Nuxt Middleware testing

Is there any way to test middleware (specifically redirecting from unauthorized routes based on a user attribute.

I am working with Nuxt Test Utils in Nuxt 4.0.3

In my middleware I have:
const { user } = useAuth();

if (isAdminRoute && !ADMINS.includes(user.value.email)) {
return navigateTo("/");
}


Now in my test file I want to test whether non admin users get redirected.

I tried mocking useAuth as mentioned in the docs, but it doesnt seem to register on middleware

import { vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

const { useAuthMock } = vi.hoisted(() => {
return {
useAuthMock: vi.fn(() => {
return { user: { email: 'dwadwadwa' } }
})
}
})

mockNuxtImport('useAuth', () => {
return useAuthMock
})

// Then, inside a test
useAuthMock.mockImplementation(() => {
return { user: { email: 'somethingelse@example.com' } }
})
`

Is there anyway to do this, I would love to test my components and routes with different users? Wondering if this is a bug in 4.0.3 or how its supposed to be. Thanks in advance🙏
Was this page helpful?