Skip to content

Testing Query Consumers

Tests are easier to trust when they control when a request settles instead of sleeping until the network might be done. Give each test its own query instance and a fetcher you can resolve or reject deliberately. Assert the caller’s result, stored data, and rendered output separately: those are related but not identical contracts.

These examples use the published imports from @studiolambda/query, not repository aliases or mocks of Query’s internals.

In a TypeScript application that already has Query installed, install Vitest and a DOM environment:

Terminal window
npm install --save-dev vitest happy-dom

For the React example, also install React/React DOM 19.2+ and their TypeScript definitions if the application does not already have them. Run the following files with:

Terminal window
npx vitest run --environment happy-dom

The browser-like environment supplies APIs such as CustomEvent. The examples construct deferred promises directly, so they do not require Promise.withResolvers support in the test runtime.

Create src/query.test.ts. This complete test checks both promise identity and the final cached value without contacting a server:

src/query.test.ts
import { it, vi } from 'vitest'
import { createQuery } from '@studiolambda/query'
it('shares a pending profile request', async ({ expect }) => {
let resolveRequest: (value: string) => void = () => {}
const pending = new Promise<string>((resolve) => {
resolveRequest = resolve
})
const fetcher = vi.fn(() => pending)
const query = createQuery({ fetcher, expiration: () => 60_000 })
const first = query.query<string>('profile')
const second = query.query<string>('profile')
expect(first).toBe(second)
expect(fetcher).toHaveBeenCalledTimes(1)
resolveRequest('Ada')
expect(await first).toBe('Ada')
expect(await query.snapshot('profile')).toBe('Ada')
expect(query.keys('resolvers')).toEqual([])
})

The fake proves request sharing and cache publication. It does not prove your HTTP endpoint, credentials, JSON validation, or CORS setup works. Test those boundaries separately.

To verify dependent edits, append this test to the same file:

it('derives queued changes from preceding committed data', async ({ expect }) => {
const query = createQuery()
query.hydrate('selected-count', 0)
const first = query.mutate<number>('selected-count', (previous) => (previous ?? 0) + 1)
const second = query.mutate<number>('selected-count', (previous) => (previous ?? 0) + 1)
expect(await Promise.all([first, second])).toEqual([1, 2])
expect(await query.snapshot('selected-count')).toBe(2)
})

Use explicit hydration expiration for tests that need a valid cached entry. Omit it for immediately stale data. Do not wait two real seconds just to cross the default freshness deadline. If you are testing timer-derived UI itself, use controlled timers in an isolated suite and restore them during cleanup.

For a fetch/write race, hold a fetch pending, commit a mutation or hydration, then settle the old fetch. Assert that the original caller settles with its own result while the snapshot remains the newer local value. For failure, attach expect(promise).rejects before triggering rejection or abort so it cannot become an unhandled rejection.

Create src/Profile.test.tsx. Passing { query } directly keeps this hook test isolated without a provider. Use a provider in tests whose subject is context or broadcast ownership.

The test tells React that this environment supports act. In a larger suite, put that assignment in your test runner’s shared setup file instead.

src/Profile.test.tsx
import { it } from 'vitest'
import { act, Suspense } from 'react'
import { createRoot } from 'react-dom/client'
import { createQuery } from '@studiolambda/query'
import { useQuery } from '@studiolambda/query/react'
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
it('renders a resolved profile', async ({ expect }) => {
const query = createQuery()
query.hydrate('profile', 'Ada', { expiration: () => 60_000 })
const container = document.createElement('div')
const root = createRoot(container)
/** A reader scoped only to this test's instance. */
function Profile() {
return <span>{useQuery<string>('profile', { query }).data}</span>
}
try {
await act(async () => {
root.render(<Suspense fallback="Loading"><Profile /></Suspense>)
})
expect(container.textContent).toBe('Ada')
await act(async () => {
await query.mutate('profile', 'Grace', { expiration: () => 60_000 })
})
expect(container.textContent).toBe('Grace')
} finally {
await act(async () => root.unmount())
}
})

Await act() around render and subsequent updates, and always unmount the root. This test intentionally supplies a valid seed and successful updates; use an actual error boundary when testing an initial rejected read. For a fresh lifecycle test, hold the initial request pending and assert the fallback, resolve it inside act, then assert output and fetch count across retries, siblings, and remounts.

Observe the operation you actually triggered

Section titled “Observe the operation you actually triggered”

query.next() listens for refetching, not every cache update. Register it before a triggering action. Do not await it for an unexpired cache hit or a mutation that emits no fetch event; await the action or the matching once() event instead.

For background failure, assert that the keyed error listener receives the reason and the old rendered value remains. For an explicit failed action, assert the promise rejection separately. Status booleans are limited event hints, not a reliable substitute for waiting on the promise under test.

Finally, dispose subscriptions and caller-created channels, restore global mocks and fake timers, and avoid overlapping React act scenarios in concurrent tests. An isolated query instance per test prevents cached data and abandoned fresh selections from leaking across cases.