Skip to content

Composable Tests

Guide for testing PIP AI composables.

Setup

Tests mock Supabase and other external dependencies. See tests/setup.ts for the global mock configuration.

Pattern

typescript
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { ref } from 'vue'

describe('useExample', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('should fetch items', async () => {
    // Arrange
    const mockData = [{ id: '1', name: 'Test' }]
    vi.mocked(supabase.from).mockReturnValue({
      select: vi.fn().mockReturnValue({
        eq: vi.fn().mockResolvedValue({ data: mockData, error: null })
      })
    })

    // Act
    const { items, fetchItems } = useExample(ref('project-id'))
    await fetchItems()

    // Assert
    expect(items.value).toEqual(mockData)
  })
})

Mocking Supabase

The global setup mocks useSupabaseClient:

typescript
// tests/setup.ts
vi.mock('#imports', () => ({
  useSupabaseClient: vi.fn(() => mockSupabaseClient),
  useSupabaseUser: vi.fn(() => ref(mockUser)),
}))

Testing Reactive State

typescript
it('should update loading state', async () => {
  const { isLoading, fetchData } = useExample(ref('id'))

  expect(isLoading.value).toBe(false)

  const promise = fetchData()
  expect(isLoading.value).toBe(true)

  await promise
  expect(isLoading.value).toBe(false)
})

Built with VitePress