---
title: "Test pages over a mock backend"
description: "Render your pages and the packaged components over a mock backend and session in Vitest: signed in, signed out, loading and failed, with no deployment and no network."
canonical_url: "https://nuxt-backend.dev/docs/develop/testing/pages"
---
# Test pages over a mock backend

> Render your pages and the packaged components over a mock backend and session in Vitest: signed in, signed out, loading and failed, with no deployment and no network.

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 page or a component in Vitest, in every state a person can see it in, with no deployment and no `vi.mock`.

- **What powers it natively:** [`@nuxt/test-utils`](https://nuxt.com/docs/getting-started/testing), which runs a test inside a Nuxt app, and Vue Test Utils, which mounts components.
- **What the package adds:** `nuxt-backend/test-utils`, a fake backend and session that every composable, packaged component and guard reads from.

The entry is experimental ([Stability](https://nuxt-backend.dev/docs/ship/releases/stability#the-experimental-tier)): the mock answers the way the auth and billing flows answer today, and follows them as they move.

## Set up the project

Add Vitest with `@nuxt/test-utils`, a DOM and, for the [accessibility check](#check-accessibility), axe-core:

```bash
npm install -D vitest @nuxt/test-utils @vue/test-utils happy-dom axe-core
```

Then add a project whose files see the mock:

```ts [vitest.config.ts]
import { defineConfig } from 'vitest/config'
import { defineVitestProject } from '@nuxt/test-utils/config'
import { backendTestAliases } from 'nuxt-backend/test-utils'

export default defineConfig({
  test: {
    projects: [
      await defineVitestProject({
        resolve: { alias: backendTestAliases() },
        test: {
          name: 'app',
          include: ['test/app/**/*.test.ts'],
          environment: 'nuxt',
          environmentOptions: { nuxt: { domEnvironment: 'happy-dom' } },
        },
      }),
    ],
  },
})
```

`backendTestAliases()` returns Vite aliases for three imports:

- `#convex/auth-client`, the auth client the session is built on, becomes one that answers from the mock.
- `nuxt-convex-module/client` and `nuxt-convex-module/vue` become the base module's own entry with every export kept, so your explicit imports from it still work.

A module of your own that imports a custom auth client by its path, not through `#convex/auth-client`, still reaches the real client. The aliases apply where Vite transforms the package and the base module, which the `nuxt` environment does for every Nuxt module. So use them in a project from `defineVitestProject`, or a single `defineVitestConfig`. A test that needs a live deployment belongs in a project without them.

## Write a test

`createBackendMock(state)` makes the mock everything reads from. Make one per test, unmount what each test mounted, and forget the mock after it:

```ts [test/app/pricing.test.ts]
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { enableAutoUnmount, flushPromises } from '@vue/test-utils'
import { createBackendMock, resetBackendMock } from 'nuxt-backend/test-utils'
import { afterEach, expect, test } from 'vitest'
import { PricingTable } from '#components'

enableAutoUnmount(afterEach)
afterEach(() => resetBackendMock())

test('a subscriber cancels the plan they are on', async () => {
  const backend = createBackendMock({
    user: { name: 'Ada' },
    queries: {
      'billing:getPricing': {
        plans: [{ key: 'pro', name: 'Pro', description: null, retired: false, features: [], featureKeys: [], prices: { month: { productId: 'prod_pro', amount: 900, currency: 'eur', monthly: 900 } } }],
        packs: [],
      },
      'billing:getCurrentSubscription': { id: 'sub_1', status: 'active', productId: 'prod_pro' },
    },
  })
  backend.stub('billing:cancelSubscription', () => null)

  const table = await mountSuspended(PricingTable, { props: { plans: [{ key: 'pro' }] } })
  // Cancelling takes one step: the button opens it, and its one button confirms.
  await table.find('[data-intent="cancel"]').trigger('click')
  await table.find('[data-pricing="confirm-cancel"]').trigger('click')
  await flushPromises()
  expect(backend.callsTo('billing:cancelSubscription')).toEqual([{ atPeriodEnd: true }])

  // The state is reactive: the table follows, as it follows the deployment.
  backend.signOut()
  await flushPromises()
  expect(table.find('[data-intent="sign-in"]').exists()).toBe(true)
})
```

A mock shared by every test of a file goes in `beforeEach(() => { backend = createBackendMock({ … }) })`. Mount with `mountSuspended`: it copies the Nuxt app's provides, where each new mock is provided.

### Mount without Nuxt

A plain `mount()` starts an app of its own, so pass the mock to it:

```ts [test/app/dashboard.test.ts]
import { mount } from '@vue/test-utils'
import { backendMockProvides } from 'nuxt-backend/test-utils'

const page = mount(Dashboard, { global: { provide: backendMockProvides() } })
```

Without it, a plain `mount()` reaches the mock only where a composable in its tree provides it on the way. A composable given an explicit `{ api }` and the base module's `<Authenticated>` don't.

## The state you give the mock

<field-group>
<field name="user" type="Partial<BackendMockUser> | null">

The signed-in account, its missing fields filled in (`user-1`, `Ada Lovelace`, `ada@example.com`, role `'user'`). Left out or `null`: signed out.

</field>

<field name="workspaces" type="Array<{ id, name?, slug?, role?, members? }>">

The account's workspaces and its role in each. Default: one personal workspace it owns, as sign-up makes it.

</field>

<field name="activeWorkspace" type="string | null">

The active workspace's id. Default: the first one.

</field>

<field name="queries" type="Record<string, unknown>">

Query results by function name (`'billing:getCredits'`): a value, or a function of the query's arguments. A query with no entry is still loading.

</field>

<field name="invitations / passkeys" type="array">

Invitations sent to the account, and its passkeys.

</field>

<field name="isLoading / session" type="boolean / object">

A session still being read (no account yet), and session fields such as `impersonatedBy`.

</field>
</field-group>

## What the mock answers

- **Queries** read `backend.state.queries`. Change an entry and every component reading it re-renders.
- **Mutations and actions** are recorded in `backend.calls`, and `backend.callsTo(name)` lists their arguments. One answers what `backend.stub(name, args => …)` returns. Without a stub it resolves `undefined` and warns once, so stub every call whose answer the page uses.
- **The auth client** answers `{ data, error }` from the state, as the real one does. A code or a passkey signs in, `signOut` signs out, and switching, creating, leaving and joining a workspace and the passkey methods change the state. It refuses what the server refuses, with the same status and code: a workspace the account is not in, leaving one it alone owns, an expired invitation or one sent to someone else, an unknown passkey. Stub or fail a method by its path: `backend.stub('signIn.emailOtp', …)`.
- **Failures:** `backend.fail(name, error)` makes a query read `error`, a mutation or action reject with it, and an auth method answer `{ data: null, error }`. A session read fails by its hook's name, and a failed session reads as signed out (the example below).
- **The session:** `backend.signIn(fields)` and `backend.signOut()` move it, and every field of `backend.state` can be set directly. Ids the mock creates (`workspace-mock-1`, …) are counted per mock.

```ts [test/app/dashboard.test.ts]
backend.fail('billing:getCredits', new Error('offline')) // the query reads the error
backend.fail('useSession', { status: 500 }) // the session read fails: signed out
```

## What reads the mock

- **The package:** every composable, with or without an explicit `{ api }`, and every packaged component and page. `useConnectionState` reads as connected.
- **The base module:** `useQuery`, `useQueries`, `useMutation`, `useAction`, `useConvexAuth`, `<Authenticated>`, `<Unauthenticated>`, `<AuthLoading>`, `<StorageImage>` (its URL query), and the page guards (`definePageMeta({ auth })`) in the browser.
- **Paginated queries** (`usePaginatedQuery`) read each page from `state.queries` like any query. Give it a function of the arguments that answers `{ page, isDone, continueCursor }` for the `paginationOpts.cursor` it is asked for.
- **Not covered:** uploads (`useUpload`), optimistic updates (ignored), anything that runs on the server (`useAsyncQuery`, preloaded queries, server routes, the middleware's server half), and the package's HTTP routes, such as the AI stream `useAiStream` reads. Test those in [convex-test](https://nuxt-backend.dev/docs/develop/testing/functions) or [end to end](https://nuxt-backend.dev/docs/develop/testing/e2e).

<note>

The mock stands in through the base module's supported seams (`nuxt-convex-module` `^0.14.0`, the range this package depends on): the `#convex/auth-client` alias its session layer loads the auth client from, and `resetBetterAuthState` from `nuxt-convex-module/testing`, which `resetBackendMock()` calls between tests. The base module loads the auth client on first use; the mock's loads as the app starts, so a test's first session read already follows it.

</note>

## Check accessibility

axe-core runs on anything rendered over the mock:

```ts [test/app/pricing.test.ts]
import axe from 'axe-core'

const table = await mountSuspended(PricingTable, { props: { plans: [{ key: 'pro' }] }, attachTo: document.body })
const { violations } = await axe.run(table.element, {
  runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'] },
})
expect(violations).toEqual([])
```

A DOM without layout leaves contrast undecided, so check contrast in a browser: the package's own [axe-core smoke](https://nuxt-backend.dev/docs/build/ui/accessibility#what-is-tested) runs the starter's pages in Chromium, and an [end-to-end test](https://nuxt-backend.dev/docs/develop/testing/e2e) can do the same for yours.

## Test your emails

`renderEmail` renders one of the emails the package sends, as `setupEmail` with the same options would, with no deployment: the template in effect, in the shared layout, in a recipient's language. Give it what your `backend/email.ts` gives `setupEmail`:

```ts [test/emails.test.ts]
import { renderEmail } from 'nuxt-backend/test-utils'
import { expect, it } from 'vitest'
import de from '../i18n/locales/de.json'

it('invites in German, to the German page', async () => {
  const message = await renderEmail('invite', {
    email: 'grace@example.com',
    url: 'https://app.example.com/accept-invitation?id=1',
    inviterName: 'Ada',
    inviterEmail: 'ada@example.com',
    workspaceName: 'Acme',
    role: 'member',
  }, { locale: 'de', messages: { de }, localePaths: 'prefix_except_default', siteUrl: 'https://app.example.com' })
  expect(message.subject).toBe('Tritt Acme bei')
  expect(message.html).toContain('https://app.example.com/de/accept-invitation?id=1')
})
```

[Send email in each reader's language](https://nuxt-backend.dev/docs/build/email/templates/languages) covers the options.

## Related

- [Test your app](https://nuxt-backend.dev/docs/develop/testing): which test fits which change.
- [Test backend functions](https://nuxt-backend.dev/docs/develop/testing/functions): the other half, in `convex-test`.
- [Run end-to-end tests](https://nuxt-backend.dev/docs/develop/testing/e2e): the real app in a browser.
- [Accessibility](https://nuxt-backend.dev/docs/build/ui/accessibility): what the packaged UI is held to.
- [Testing in Nuxt](https://nuxt.com/docs/getting-started/testing): `@nuxt/test-utils` itself.


## Sitemap

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