Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 32 ยท Quality

Testing Nuxt Apps

Learn how to test a Nuxt app: unit tests with Vitest, components with @nuxt/test-utils, mocking fetch and composables, server routes, and end-to-end tests with Playwright.

A Nuxt app is several programs in one: Vue components that render in a browser, composables that run on both sides, and a Nitro server with API routes. A good test suite does not try to cover all of it with one tool. It uses fast, small tests for logic, component tests for what a piece of UI shows, and a few end-to-end tests that drive a real browser through the paths that must never break.

This lesson maps each kind of code to a kind of test, shows how Vitest and @nuxt/test-utils are set up, and then shows the technique that pays off most: keeping logic in plain functions with dependencies passed in, so a test can replace the network with a fake. The Nuxt, Vitest and Playwright code is read-only because none of them can run on this site. The runnable examples are real tests written with Node's built-in node:test runner, for logic written the same way you would write it in server/utils or a composable.

Match the test to the code

Plain logic Validators, formatters, handlers. Test as functions.
Components Mount in a Nuxt test environment and check the output.
Whole flows Playwright clicks through a real running app.

Many cheap tests, a few expensive ones.

1 / 2

Setting up Vitest with @nuxt/test-utils

Nuxt's own tooling uses Vitest as the test runner and ships helpers in the @nuxt/test-utils package. A typical setup looks like this (read-only):

TypeScript
// vitest.config.ts (read-only)
import { defineVitestConfig } from "@nuxt/test-utils/config";

export default defineVitestConfig({
  test: {
    environment: "nuxt",
  },
});

With environment: "nuxt", your tests run inside a Nuxt runtime, so auto-imports such as ref, useState and useRoute work and useNuxtApp() returns a real app. Many projects keep two groups of tests: fast unit tests that do not need Nuxt at all (plain Node environment), and tests that do. You can switch the environment per file with a comment at the top of the file:

TypeScript
// @vitest-environment nuxt

Test files normally end in .test.ts and live next to the code or in a tests/ folder. Run them with npx vitest.

Unit tests for logic

Most of your logic is plain TypeScript: price formatting, slug creation, an input validator. These need no Nuxt at all:

TypeScript
// utils/slugify.test.ts (read-only)
import { describe, expect, it } from "vitest";
import { slugify } from "./slugify";

describe("slugify", () => {
  it("lowercases and joins words with dashes", () => {
    expect(slugify("Hello Nuxt World")).toBe("hello-nuxt-world");
  });

  it("drops characters that are not allowed in a URL", () => {
    expect(slugify("Rock & Roll!")).toBe("rock-roll");
  });
});

The cheapest way to make code testable is to keep it free of Nuxt-specific calls. A function that takes its inputs as arguments is easy to test; one that calls useRuntimeConfig() inside is harder.

Testing components

To test a component that depends on Nuxt (auto-imports, <NuxtLink>, plugins), use mountSuspended from @nuxt/test-utils/runtime. It mounts the component inside the Nuxt app and waits for any async setup:

TypeScript
// components/ProductCard.test.ts (read-only)
// @vitest-environment nuxt
import { describe, expect, it } from "vitest";
import { mountSuspended } from "@nuxt/test-utils/runtime";
import ProductCard from "./ProductCard.vue";

describe("ProductCard", () => {
  it("shows the name and a formatted price", async () => {
    const wrapper = await mountSuspended(ProductCard, {
      props: { name: "Desk lamp", priceCents: 4999 },
    });

    expect(wrapper.text()).toContain("Desk lamp");
    expect(wrapper.text()).toContain("$49.99");
  });
});

Test what the user sees and does: text, roles, what happens after a click. Avoid asserting on internal refs or private method names, because those change whenever you refactor, while the visible behavior should not.

Mocking composables and fetch

Two kinds of replacements come up constantly. To replace an auto-imported composable, use mockNuxtImport; to fake an API route that the component calls with useFetch, use registerEndpoint:

TypeScript
// pages/products.test.ts (read-only)
// @vitest-environment nuxt
import { it, expect } from "vitest";
import { mockNuxtImport, mountSuspended, registerEndpoint } from "@nuxt/test-utils/runtime";
import ProductsPage from "./products.vue";

mockNuxtImport("useRoute", () => () => ({ query: { sort: "price" } }));

registerEndpoint("/api/products", () => [
  { id: 1, name: "Desk lamp" },
  { id: 2, name: "Notebook" },
]);

it("lists the products from the API", async () => {
  const wrapper = await mountSuspended(ProductsPage);
  expect(wrapper.text()).toContain("Notebook");
});

The component code is unchanged: it still calls useFetch("/api/products"), but the request is answered by the registered endpoint instead of a real server, so the test is fast and repeatable. Mocks must be declared at the top level of the test file, because Vitest hoists them.

Pass the network in, and the test gets easy

Not everything needs a Nuxt environment. If you write a data function that receives its fetch function, a test can hand in a fake. The example below does exactly that with Node's real test runner. The code under test has the shape of a helper you might keep in server/utils or a composable: validate input, call an API, and map the result. The fake fetch is built with mock.fn, which records every call, so the test can also assert that a bad input never reached the network.

Node.js Testing a data helper with a fake fetch (node:test)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Four tests run in a few milliseconds with no server, no port and no browser. The last one covers a failure that is hard to trigger on demand with a real network, which is a main reason to inject the fetch function. In a real project the file would be product-service.test.ts, you would import describe, it and vi from Vitest (vi.fn() is the counterpart of mock.fn()), and nothing else about the idea changes.

Fixing the clock

Time is the other classic source of flaky tests. A search box that waits 300 ms after the last keystroke before calling the API should not make your test wait 300 ms of real time. Node's runner (and Vitest, with vi.useFakeTimers()) can replace the timers with a clock you advance by hand:

Node.js Testing a debounced search with a fake clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The fake clock makes both tests finish instantly and exactly: at 299 ms nothing has happened, at 300 ms the single search fires, and only with the final term.

Testing server routes

There are two options. The first is the same trick as above: keep the route file thin, move the work into a function in server/utils, and test the function. The route becomes two or three lines of glue. The second is a real request against a real Nitro server, which @nuxt/test-utils/e2e can start for you:

TypeScript
// tests/api.test.ts (read-only)
import { describe, expect, it } from "vitest";
import { $fetch, setup } from "@nuxt/test-utils/e2e";

describe("api", async () => {
  await setup({ server: true });

  it("rejects an invalid signup with 422", async () => {
    const error = await $fetch("/api/signup", {
      method: "POST",
      body: { email: "nope" },
    }).catch((e) => e);

    expect(error.statusCode).toBe(422);
  });
});

setup builds the project and serves it for the duration of the tests, so these tests are slower than unit tests (seconds, not milliseconds). Keep them for the contract that matters: status codes, validation, authorization (see Forms, validation and auth flows). Detailed branching logic is cheaper to test at the function level.

End-to-end tests with Playwright

End-to-end (e2e) tests open a real browser, click through your app and check the page. They catch what other tests cannot: broken routing, hydration problems, a button that is covered by another element. Playwright is the usual choice, and @nuxt/test-utils can start the Nuxt app for it. A plain Playwright test is easy to read:

TypeScript
// e2e/checkout.spec.ts (read-only)
import { expect, test } from "@playwright/test";

test("a guest can add a product to the cart", async ({ page }) => {
  await page.goto("/products");
  await page.getByRole("button", { name: "Add to cart" }).first().click();
  await expect(page.getByRole("link", { name: /cart \(1\)/i })).toBeVisible();
});

Selecting by role and visible text (getByRole, getByLabel) makes the test resemble how a person uses the page, and keeps it working when the markup changes. Playwright waits for elements automatically, so you should not add manual sleeps.

Run e2e tests against a production build (nuxt build then the preview server) whenever you can, since some problems, like hydration mismatches in Hydration and SSR pitfalls, only show up there. Keep the list short and focused on money paths, sign-in and anything that would hurt if it broke at night.

What to test (and what not to)

  • Test your logic and your decisions, not the framework. You do not need a test proving that useFetch fetches.
  • One behavior per test, with a name that reads like a sentence.
  • Avoid shared mutable state between tests; create what you need in each one.
  • Do not freeze the exact HTML of a component in a snapshot for everything. Large snapshots break on every change and get approved without reading.
  • Fix the sources of randomness: time, random numbers and ids, otherwise tests pass today and fail on Tuesday.
  • Run the suite in CI on every push; a test nobody runs does not protect anything.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which helper mounts a component inside the running Nuxt app, with auto-imports and plugins available?

    mountSuspended wraps the mount so the component runs in the Nuxt environment and waits for async setup. It is the standard helper for components that use Nuxt features.
  2. 2. How does registerEndpoint help a component test?

    The component still calls useFetch as usual, but the request is handled by your registered handler, which makes the test fast and predictable.
  3. 3. Why is it useful to pass a fetch function into a helper instead of calling the global fetch inside it?

    Injecting the dependency lets a test hand in a fake that returns data or fails on demand, and records the calls, without any network.
  4. 4. Which test is the best fit for checking that a sign-in flow works across several pages?

    Flows across pages involve routing, cookies and real rendering, which only an end-to-end test in a real browser exercises together.
  5. 5. Which Playwright locator best matches how a person finds a button?

    Role and name locators describe what the user sees, so they keep working when the markup or class names change.

Summary

  • Match test type to code: plain functions for logic, component tests for UI, a few end-to-end tests for whole flows.
  • @nuxt/test-utils adds a Nuxt Vitest environment, mountSuspended, mockNuxtImport and registerEndpoint for components, and setup plus $fetch for server routes.
  • Write logic so its dependencies (fetch, clock, store) are passed in; tests then supply fakes and check the calls.
  • Playwright tests should use role and text locators, run against a build, and cover only the important paths.
  • Avoid big snapshots, shared state and unfixed randomness.

Next: Performance and Core Web Vitals