This library is in early development. Expect breaking changes.
Guides

Testing

Mock authentication in tests.

Mocking useUserSession

tests/utils.ts
import type { AuthUser } from '#nuxt-better-auth'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
import { computed, ref } from 'vue'
import { vi } from 'vitest'

export function mockAuth(user: Partial<AuthUser> | null = null) {
  mockNuxtImport('useUserSession', () => () => ({
    user: ref(user),
    session: ref(user ? { id: 'test-session' } : null),
    loggedIn: computed(() => !!user),
    ready: ref(true),
    signIn: { email: vi.fn(), social: vi.fn() },
    signOut: vi.fn(),
  }))
}

Testing Protected API Routes

server/api/protected.test.ts
import { describe, it, expect } from 'vitest'

describe('GET /api/protected', () => {
  it('returns 401 without session', async () => {
    const res = await $fetch('/api/protected', { ignoreResponseError: true })
    expect(res.statusCode).toBe(401)
  })
})