Skip to content

Testing

Since @nano_kit/query is built on top of @nano_kit/store, all testing principles and best practices for stores apply here as well.

Please refer to the Store Testing documentation for general guidelines on:

  • Mocking dependencies (Dependency Injection).
  • Testing lifecycle events (onMount).
  • Managing timers and unmount delays.

Tests often need to wait for asynchronous data fetching to resolve. Every query attaches its request as a task to its data signal, so waitTasks of that signal awaits the request with no extra setup, ensuring your assertions run only after data is loaded.

import { describe, it, expect, vi } from 'vitest'
import { waitTasks, start } from '@nano_kit/store'
import { client, queryKey } from '@nano_kit/query'
const TestKey = queryKey('test')
it('should fetch and update state', async () => {
/* 1. Create a client, no task setup is needed */
const { query } = client()
/* Mock fetcher */
const fetcher = vi.fn().mockResolvedValue('success')
/* 2. Start the query */
const [$data, $error, $loading] = query(TestKey, [], fetcher)
/* Mount the signal to trigger the fetch */
const stop = start($data)
expect($loading()).toBe(true)
/* 3. Wait for the request of $data to complete */
await waitTasks($data)
/* 4. Assert final state */
expect($loading()).toBe(false)
expect($data()).toBe('success')
stop()
})

waitTasks of any signal computed from $data waits for the request as well. Infinite queries and operations attach their requests to $data too. A mutation attaches each request to all of its signals, so waiting for any of them works, as does awaiting the promise returned by mutate.