28 tests across 4 spec files. Vitest + happy-dom configured with Nuxt auto-import shims ($$fetch, navigateTo, defineNuxtRouteMiddleware) so stores and composables resolve cleanly outside the Nuxt runtime. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
53 lines
1.8 KiB
TypeScript
53 lines
1.8 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import { setActivePinia, createPinia } from 'pinia'
|
|
import { useAuthStore } from '../../stores/auth.store'
|
|
|
|
// The middleware calls useAuthStore() and navigateTo() as Nuxt auto-imports.
|
|
// We override the global.useAuthStore shim (set in setup.ts) with the real
|
|
// store factory so it resolves against the active Pinia instance.
|
|
// navigateTo is already vi.fn() from setup.ts.
|
|
|
|
const mockNavigateTo = vi.mocked(navigateTo as ReturnType<typeof vi.fn>)
|
|
|
|
// Load the middleware factory.
|
|
// defineNuxtRouteMiddleware is a pass-through shim that just returns the fn.
|
|
// So `adminMiddleware` will be the inner route handler function.
|
|
let adminMiddleware: () => unknown
|
|
|
|
beforeEach(async () => {
|
|
setActivePinia(createPinia())
|
|
vi.clearAllMocks()
|
|
|
|
// Bind useAuthStore to the global so middleware can call it as an auto-import
|
|
global.useAuthStore = useAuthStore as any
|
|
|
|
// Re-import the middleware fresh each test to get the current global binding
|
|
const mod = await import('../../middleware/admin?t=' + Date.now())
|
|
adminMiddleware = mod.default
|
|
})
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// admin middleware
|
|
// ---------------------------------------------------------------------------
|
|
describe('admin middleware', () => {
|
|
it('redirects non-admin users to "/"', () => {
|
|
const auth = useAuthStore()
|
|
// Non-admin user
|
|
auth.user = { id: 2, email: 'bob@example.com', displayName: 'Bob', role: 'user' }
|
|
|
|
adminMiddleware()
|
|
|
|
expect(mockNavigateTo).toHaveBeenCalledWith('/')
|
|
})
|
|
|
|
it('allows admin users through without redirecting', () => {
|
|
const auth = useAuthStore()
|
|
// Admin user
|
|
auth.user = { id: 1, email: 'alice@example.com', displayName: 'Alice', role: 'admin' }
|
|
|
|
adminMiddleware()
|
|
|
|
expect(mockNavigateTo).not.toHaveBeenCalled()
|
|
})
|
|
})
|