---
title: "Test backend functions"
description: "Run your Convex functions in convex-test with every component the scaffold mounts, call them as a signed-in person in a workspace, upload files, seed plans and credits, run scheduled work to the end, and assert each refusal by its code."
canonical_url: "https://nuxt-backend.dev/docs/develop/testing/functions"
---
# Test backend functions

> Run your Convex functions in convex-test with every component the scaffold mounts, call them as a signed-in person in a workspace, upload files, seed plans and credits, run scheduled work to the end, and assert each refusal by its code.

Version: nuxt-backend 0.6.x · Tab: Develop · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

Test a query, a mutation or an action in Vitest, with no deployment and no provider.

- **What powers it natively:** [`convex-test`](https://docs.convex.dev/testing/convex-test), Convex's mock of a deployment, which runs your functions against an in-memory database.
- **What the package adds:** `nuxt-backend/test`. It mounts the packaged `backend` component and every component the scaffold mounts, signs callers in with the claims a real session carries, and covers what a backend test needs around them: uploads, billing state, scheduled work and storage URLs.

## Your app under test

Install `convex-test` beside Vitest and Convex's edge runtime. `convex-test` is an optional peer of the package, so an app with no tests never installs it:

```bash
npm install -D vitest convex-test @edge-runtime/vm
```

Give the backend tests a Vitest project that runs in the edge runtime, as the deployment does:

```ts [vitest.config.ts]
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    projects: [{
      test: {
        name: 'backend',
        include: ['backend/**/*.test.ts'],
        environment: 'edge-runtime',
      },
    }],
  },
})
```

`defineBackendTestApp(schema, modules)` returns a function that builds a fresh instance. Every component the scaffold mounts is registered under the name `convex.config.ts` gives it: `backend`, and the official components beside it, such as `polar`, `rateLimiter` and `workflow` ([What the scaffold mounts](https://nuxt-backend.dev/docs/start/concepts/how-it-works#the-scaffolded-convexconfigts)). Call it once per test, so no test sees another's rows.

It also sets the variables a deployment holds, once, when `defineBackendTestApp` runs, for each one your test file has not set by then: `AUTH_SECRET` (a test value, which signed URLs, share links and invite codes are keyed with), `SITE_URL` (`https://app.test`) and `CONVEX_SITE_URL` (`https://convex.test`). `vi.stubEnv` changes them like any variable: `vi.stubEnv('SITE_URL', undefined)` unsets one for the instances you make after it, so a test of what happens without it sees it missing, and `vi.unstubAllEnvs()` puts the test values back.

`asUser(t, options)` creates an account in the component's auth tables and returns the instance signed in as it. The caller looks the way a real sign-in leaves one: the role `'user'`, and a personal workspace it owns and has active.

```ts [backend/todos.test.ts]
import { asUser, defineBackendTestApp, seedWorkspace } from 'nuxt-backend/test'
import { expect, test } from 'vitest'
import { api } from './_generated/api'
import schema from './schema'

const testApp = defineBackendTestApp(schema, import.meta.glob('./**/*.ts'))

test('a member adds a todo to their workspace', async () => {
  const ada = await asUser(testApp())
  await ada.mutation(api.todos.create, { text: 'Ship it' })
})

test('everyone in the workspace is listed', async () => {
  const t = testApp()
  const workspace = await seedWorkspace(t)
  const owner = await asUser(t, { workspace, workspaceRole: 'owner' })
  await asUser(t, { workspace })
  const workspaceMembers = await owner.query(api.auth.listWorkspaceMembers, {})
  expect(workspaceMembers?.members).toHaveLength(2)
})
```

`asUser` takes these options:

<field-group>
<field name="email / name" type="string">

The account. Default: a fresh `user-<n>@example.com`, named after it.

</field>

<field name="role" type="string">

The app-wide role, such as `'admin'`. Default: `'user'`, the role every new account gets.

</field>

<field name="workspace" type="boolean | string">

The active workspace. Default: a personal one the user owns, made the way sign-in makes it. A workspace id (from `seedWorkspace(t)` or another `asUser`) adds them to that one instead; `false` leaves them in none, as after leaving every workspace.

</field>

<field name="workspaceRole" type="string">

Their role there. Default: `'owner'` of their own, `'member'` of another.

</field>

<field name="impersonatedBy" type="string">

The admin's user id, for a session an admin opened as this user.

</field>
</field-group>

The caller is `t.withIdentity(...)` with the claims a real session token carries: the account's fields, `role` included, plus the active workspace, `sessionId` and `impersonatedBy`. The issuer is `CONVEX_SITE_URL` when the test sets it, so `tokenIdentifier` reads as in production. The function tiers, the billing entity and `listSessions` resolve exactly as they do for a real caller, and a contract test in the package keeps the claims in step with the real tokens. The caller also carries `userId`, `email`, `workspaceId` and `sessionId` for your assertions.

<note>

The helpers on this page are experimental ([Stability](https://nuxt-backend.dev/docs/ship/releases/stability#the-experimental-tier)): the claims follow the auth flows, and the rest convex-test's scheduler and storage, which may still move.

</note>

## Assert a refusal

A tier refuses with a code from the error catalog, so a test never matches a message. Read the code with `getBackendError`:

```ts [backend/todos.test.ts]
import { getBackendError } from 'nuxt-backend/functions'

test('a visitor cannot add a todo', async () => {
  const error = await testApp().mutation(api.todos.create, { text: 'Ship it' }).catch(e => e)
  expect(getBackendError(error)?.code).toBe('unauthenticated')
})

test('someone outside every workspace cannot add one either', async () => {
  const loner = await asUser(testApp(), { workspace: false })
  const error = await loner.mutation(api.todos.create, { text: 'Ship it' }).catch(e => e)
  expect(getBackendError(error)?.code).toBe('no_workspace')
})
```

[Errors](https://nuxt-backend.dev/docs/reference/backend/errors) lists every code, with what a page shows for each.

## Upload a file

`t.upload(file?)` sends a file into the `backend` component's storage, claimed by nobody, as the browser leaves it after posting to an upload URL, and returns its storage id. Hand that id to the function that claims it. With no file it sends a valid 2 × 2 PNG (`TEST_PNG`); it also takes bytes, a `Blob` or text, and `{ type }` for the type the browser would send:

```ts [backend/photos.test.ts]
import { asUser, defineBackendTestApp } from 'nuxt-backend/test'
import { expect, test } from 'vitest'
import { api } from './_generated/api'
import schema from './schema'

const testApp = defineBackendTestApp(schema, import.meta.glob('./**/*.ts'))

test('a text file is refused as a photo', async () => {
  const t = testApp()
  const ada = await asUser(t)
  const fileId = await t.upload('not a photo at all')
  await expect(ada.mutation(api.photos.attach, { fileId })).rejects.toThrow()
})
```

`upload(t, file, options, name)` is the same as a function, for an instance you built yourself or a component mounted under another name.

`t.fileExists(storageId)` reads whether a file is still in that storage: `false` once something deleted it, and for an id it never held. Assert what a deletion, a sweep or an account's erasure left behind with it; `fileExists(t, storageId, name)` is the same as a function:

```ts [backend/photos.test.ts]
test('removing a photo deletes its file', async () => {
  const t = testApp()
  const ada = await asUser(t)
  const fileId = await t.upload()
  await ada.mutation(api.photos.attach, { fileId })
  await ada.mutation(api.photos.remove, { fileId })
  expect(await t.fileExists(fileId)).toBe(false)
})
```

## Run scheduled work to the end

A claimed upload is checked in the background, a job's steps and a workflow run as scheduled functions, and an email goes out from a batch. `drain(t, vi)` runs every scheduled function to the end, one at a time: between two, the clock moves to the next timer and no further, so a function that stores a file never runs while another commits. It needs fake timers, and real ones back after each test, a failing one included:

```ts [backend/photos.test.ts]
import { drain } from 'nuxt-backend/test'
import { afterEach, vi } from 'vitest'

afterEach(() => vi.useRealTimers())

test('a claimed photo is served once its check ran', async () => {
  vi.useFakeTimers()
  const t = testApp()
  const ada = await asUser(t)
  const fileId = await t.upload()
  await ada.mutation(api.photos.attach, { fileId })
  await drain(t, vi)
  expect(await ada.query(api.photos.list, {})).toEqual([expect.objectContaining({ url: expect.any(String) })])
})
```

It throws when the functions keep scheduling more past `maxSteps` timers (5000 by default, `drain(t, vi, { maxSteps })`): a function that schedules itself forever never drains.

`drain(t, vi, { until })` stops as soon as `until` holds, checked after each step: drain to the moment that matters, change something, then drain on. It throws when every scheduled function ran and `until` never held:

```ts [backend/strips.test.ts]
test('a canceled strip stops after the panel it is drawing', async () => {
  vi.useFakeTimers()
  const t = testApp()
  const ada = await asUser(t)
  const stripId = await ada.mutation(api.strips.create, { idea: 'A fox who wants to fly', panels: 4 })
  const jobId = (await ada.query(api.strips.get, { id: stripId }))!.jobId!
  await drain(t, vi, { until: async () => (await ada.query(api.jobs.getJob, { jobId }))?.status === 'running' })
  await ada.mutation(api.jobs.cancelJob, { jobId })
  await drain(t, vi)
  expect(await ada.query(api.jobs.getJob, { jobId })).toMatchObject({ status: 'canceled' })
})
```

## Serve stored files with no network

A model handed a photo by URL, or your own action, fetches a file's storage URL. Under test that URL names a deployment that does not exist. `stubStorageFetch()` answers `fetch` for every file your functions stored, uploads included, with its bytes and type, and throws `No network under test` for any other request. It returns the function that puts `fetch` back:

```ts [backend/photos.test.ts]
import { stubStorageFetch } from 'nuxt-backend/test'
import { afterEach, beforeEach } from 'vitest'

let restoreFetch: () => void
beforeEach(() => {
  restoreFetch = stubStorageFetch()
})
afterEach(() => restoreFetch())
```

Pass `{ network }` to answer other requests yourself: `stubStorageFetch({ network: request => Response.json({ ok: true }) })`.

## Give an account plans and credits

`seedBilling(t, entityId, billing)` leaves a billing entity's cache as a sync from the provider would: `products` (the provider's product ids), `features` (the keys `hasFeature` reads) and `credits` (a balance per meter id). `customer: true` also makes the provider's customer, for a flow that charges or opens the portal. `seedCredits(t, entityId, meterId, balance)` sets one meter and keeps the rest. No provider is called:

```ts [backend/exports.test.ts]
import { asUser, seedBilling, seedCredits } from 'nuxt-backend/test'

const COINS = 'meter_coins' // your catalog's meter id

test('an export spends a coin, and refuses with none left', async () => {
  const t = testApp()
  const ada = await asUser(t)
  await seedBilling(t, ada.workspaceId!, { features: ['export'], credits: { [COINS]: 1 } })
  await ada.action(api.exports.run, {})
  await seedCredits(t, ada.workspaceId!, COINS, 0)
  await expect(ada.action(api.exports.run, {})).rejects.toThrow()
})
```

The entity is the one billing charges: the workspace by default (`ada.workspaceId`), the account with `billTo: 'user'` (`ada.userId`).

## Fake the billing provider

A charge, a refund or a cost report reaches the billing provider as a usage event, which a test has no network for. `stubBillingProvider()` answers the provider's usage-event ingest in `fetch`, as its API would, so your real billing runs end to end: each event is kept once by its idempotency key, and the fake reports back what it took. Give the entity a customer with `seedBilling(t, entityId, { customer: true, credits })`: billing sends nothing for an entity with none, and refuses the charge `not_ready` (`no_customer`). Restore `fetch` after each test:

```ts [backend/strips.test.ts]
import { asUser, drain, seedBilling, stubBillingProvider, type TestBillingProvider } from 'nuxt-backend/test'
import { afterEach, beforeEach, expect, test, vi } from 'vitest'

const CREDITS = 'meter_credits' // your catalog's meter id
let provider: TestBillingProvider
beforeEach(() => {
  vi.useFakeTimers()
  provider = stubBillingProvider()
})
afterEach(() => {
  provider.restore()
  vi.useRealTimers()
})

test('a strip the provider cannot charge yet is done, and charged later', async () => {
  const t = testApp()
  const ada = await asUser(t)
  await seedBilling(t, ada.workspaceId!, { customer: true, credits: { [CREDITS]: 50 } })
  provider.refuse('charges', 1)
  const stripId = await ada.mutation(api.strips.create, { idea: 'A fox who wants to fly', panels: 4 })
  const jobId = (await ada.query(api.strips.get, { id: stripId }))!.jobId!
  await drain(t, vi, { until: async () => (await ada.query(api.jobs.getJob, { jobId }))?.status === 'done' })
  expect(await ada.query(api.jobs.getJob, { jobId })).toMatchObject({ charged: 0, owed: { credits: 20, givenUp: false } })
  await drain(t, vi)
  expect(provider.charges).toEqual([expect.objectContaining({ value: 20, metadata: expect.objectContaining({ stripId }) })])
})
```

The strip here renders with a kind charged by output, as on the [credits page](https://nuxt-backend.dev/docs/build/ai/jobs/credits#charge-for-what-a-job-made), that tags its charge: `job.charge(drawn * 5, { metadata: { stripId } })`.

- **provider.events** lists every event it took, in order, each key once; **charges** the ones that move credits up, **refunds** the ones that give them back (a negative `value`). Each has its `name`, the `customer` (the billing entity), its `externalId`, the `value` it moves and its `metadata`.
- **provider.refuse('charges', n)** answers the next `n` charges with a `503`, as a provider having trouble does, keeping none of them; with no `n`, every one until `provider.accept()`. `refuse('refunds', n)` does the same to refunds, and `provider.refused` counts what it refused.
- **Any other request** goes on to the `fetch` it replaced, so it composes with `stubStorageFetch()` in either order.

## Test AI calls

Under `defineBackendTestApp`, every `provider/model` id answers from a mock of the AI SDK's `ai/test`, so a test needs no key and makes no network call. A model repeats the prompt (`Test reply to: …`) at a fixed cost. A safety classifier, any id with `llama-guard` or `safeguard` in it, answers as Llama Guard does: `unsafe` and `S1` when the content it checks contains `[[unsafe]]`, `unsafe` and the codes you choose for `[[unsafe:S7]]` (`TEST_UNSAFE_CODE('S7')`, several as `'S1,S10'`), and `safe` otherwise. So a test of `ai.requireSafe`, or of `moderate` on a call, passes or refuses on purpose, and a policy that blocks some categories and records the rest is tested category by category:

```ts [backend/captions.test.ts]
test('a flagged prompt is refused before anything is spent', async () => {
  const ada = await asUser(testApp())
  const error = await ada.action(api.captions.write, { prompt: 'A fox [[unsafe]]' }).catch(e => e)
  expect(getBackendError(error)).toMatchObject({ code: 'invalid_input', data: { reason: 'content_blocked' } })
})
```

It reads an image's bytes too: an upload whose bytes carry a marker, after a valid image's, is flagged as the marker says:

```ts [backend/photos.test.ts]
import { TEST_PNG, TEST_UNSAFE_CODE } from 'nuxt-backend/test'

test('a photo the classifier flags as sexual content is refused', async () => {
  const t = testApp()
  const ada = await asUser(t)
  const fileId = await t.upload(new Uint8Array([...TEST_PNG, ...new TextEncoder().encode(TEST_UNSAFE_CODE('S12'))]))
  await expect(ada.action(api.photos.attach, { fileId })).rejects.toThrow()
})
```

In a job's step, nobody is signed in: a flag recorded there names the job's starter and owner (`ctx.job.userId`, `ctx.job.owner`).

## Mount a component of your own

A component your app mounts itself, beside the scaffold's, registers through its own test helper under the same name. Name it in `mounts`, and every instance has it:

```ts [backend/test.app.ts]
import workflow from '@convex-dev/workflow/test'
import { defineBackendTestApp } from 'nuxt-backend/test'
import schema from './schema'

// convex.config.ts mounts a second workflow as `generation`.
export const testApp = defineBackendTestApp(schema, import.meta.glob('./**/*.ts'), {
  mounts: { generation: workflow },
})
```

The helper is the default export of the component's `/test` entry; anything else throws as `defineBackendTestApp` runs.

## Register the component yourself

For a harness you build by hand, `register(t)` mounts the `backend` component alone:

```ts [backend/billing.test.ts]
import { convexTest } from 'convex-test'
import backendTest from 'nuxt-backend/test'
import { components } from './_generated/api'
import schema from './schema'

const modules = import.meta.glob('./**/*.ts')

const t = convexTest(schema, modules)
backendTest.register(t)

// Your own functions, and the component's, through the boundary:
await t.query(components.backend.billing.getByUser, { userId: 'user_1' })
```

`register(t)` mounts the all-in-one `backend` component the way `app.use(backend)` does. It registers it under its name, with its real schema, so every index and document validator applies. Its two children come with it: the email provider at `backend/resend` and the package's migrations at `backend/migrations`. Functions that read auth tables, send email or call into `components.backend` resolve under test.

```ts
function register(
  t: TestConvex<SchemaDefinition>,
  name?: string, // the mount name from convex.config.ts, default 'backend'
): void
// default export: { register, schema, modules }
```

The helper has the shape every `@convex-dev/*` component ships, so `convex-test` needs nothing extra. It uses `import.meta.glob`, so it runs under Vitest only.

<note>

The email provider's own children (its send workpools and API rate limiter) are not registered: they only run from the batch job a send schedules. Emails sent under test stay `waiting`, which is the state `cancel` and delivery-status assertions need.

</note>

## What it does not cover

- **Pages and components:** render them over a mock backend ([Test pages over a mock backend](https://nuxt-backend.dev/docs/develop/testing/pages)).
- **The providers:** no test here calls Polar or Resend: `stubBillingProvider()` stands in for the usage events a charge or a refund sends. A run that crosses a provider for real is an [end-to-end test](https://nuxt-backend.dev/docs/develop/testing/e2e).
- **Webhook signatures:** `convex-test` runs HTTP actions through `t.fetch`, but it can't sign a request the way a provider does. Test the handler's logic as a function.

## Related

- [Test your app](https://nuxt-backend.dev/docs/develop/testing): which test fits which change.
- [Authorize functions](https://nuxt-backend.dev/docs/build/auth/access/functions): the tiers these tests sign in to.
- [Errors](https://nuxt-backend.dev/docs/reference/backend/errors): every refusal code.
- [Lint backend functions](https://nuxt-backend.dev/docs/develop/testing/linting): Convex's rules over `backend/`.
- [Convex's testing guide](https://docs.convex.dev/testing/convex-test): `convex-test` itself.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
