> ## Documentation Index
> Fetch the complete documentation index at: https://docs.varianz.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Vitest

> Test with @varianz/vitest: the varianz fixture, custom matchers, session-scoped stages, and concurrency caveats.

Install `@varianz/vitest` ([instructions](/installation#typescript)) and wire it up once:

```typescript theme={null}
// test/setup.ts
import { varianzVitest } from '@varianz/vitest';

export const { test } = varianzVitest({
  // endpoint omitted: falls back to VARIANZ_REGISTRY_ADDR / VARIANZ_ENDPOINT,
  // then http://127.0.0.1:50051
  applicationName: 'my-service-tests',
});
export { describe, expect, beforeAll } from 'vitest';
export { cel } from '@varianz/vitest';
```

```typescript theme={null}
// vitest.config.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    setupFiles: ['@varianz/vitest/setup'],  // installs the custom matchers
    fileParallelism: false,                 // initRegistry is process-global
  },
});
```

Run with the [standard environment](/reference/configuration) (`VARIANZ_ENABLED=true`, and `VARIANZ_INSECURE_ALLOW_PLAINTEXT=true` for a plaintext local registry) — the fixture throws a clear error if the SDK is disabled.

## Writing tests

```typescript theme={null}
import { test, expect, cel, describe } from './setup.js';
import { PricingService } from '../src/service.js';

describe('pricing', () => {
  test('bulk discount applies at 10+', async ({ varianz }) => {
    await varianz.insert(cel(
      'pricing/calculate',
      'args.input.quantity >= 10 ' +
        '? PricingResult { totalPrice: args.input.basePrice * args.input.quantity * 0.9, discountApplied: true } ' +
        ': invoke()',
    ));

    await varianz.awaitSyncOrFail(5_000);

    // The fixture has already entered the session scope for the test body —
    // in-process calls match session stages without extra wiring.
    const out = new PricingService().calculate(input);

    expect(out.totalPrice).toBeCloseTo(108);
    await expect(varianz).toEventuallyHaveSample('price-result', { within: 5_000 });
  });
});
```

Fixtures:

* `varianz` — per-test `VarianzTestSession`. It installs a session-ID fallback in `AsyncLocalStorage` for the whole test body, so in-process VPoint calls match your stages automatically.
* `varianzClient` — worker-scoped client for advanced registry assertions (most tests don't need it).

## Custom matchers

Installed by the `@varianz/vitest/setup` file:

```typescript theme={null}
await expect(varianz).toEventuallyHaveSample('price-result', { within: 5_000 });
await expect(varianz).toHaveSampleValue('price-result', 108, { path: 'totalPrice', within: 10_000 });
```

## Session API

| Method / property             | Returns                      | Description                                                                                                       |
| ----------------------------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `sessionId`                   | `string`                     | 32-char hex session ID (for `x-varianz-id` when triggering over the network)                                      |
| `insert(stage, anchor?)`      | `Promise<string>`            | Insert a CEL stage                                                                                                |
| `awaitSync(timeoutMs?)`       | `Promise<SessionSyncResult>` | Wait for subscribers                                                                                              |
| `awaitSyncOrFail(timeoutMs?)` | `Promise<void>`              | Wait; throw on timeout or validation failure; see [zero-subscriber semantics](/testing/overview#zero-subscribers) |
| `assertSample(ident)`         | `SampleAssert`               | Fluent chain: `.within(ms)`, `.exists()`, `.hasCount(n)`, `.hasValue(path, v)`                                    |
| `getSamples()`                | `Record<string, unknown>[]`  | Raw buffered samples                                                                                              |

## Concurrency

In `describe.concurrent` / `it.concurrent` blocks, the module-level session fallback is last-write-wins and races under true parallelism. Re-establish the scope locally:

```typescript theme={null}
await varianz.run(() => service.calculate(input));
```

And keep `fileParallelism: false` — the native `initRegistry` binding can only initialize once per process.
