In the previous lesson you tested self-sufficient pieces: a function that formats, a badge, a card, a field. But most of Colmena is not like that. RoomDetailView requests the catalogue from an API that takes between 0.3 and 1.5 seconds and fails one time in ten; ReceptionClock shows the current time, which is different on every run; LoginView authenticates against the API and navigates with the router; cancelling a booking asks for confirmation with window.confirm. A test that depends on all of that will be slow, will fail at random and will not be able to check exact values. The solution is to replace those dependencies with test doubles that you control: functions that return whatever you decide, mocked modules, clocks that move forward when you tell them to and routers that live in memory. In this lesson you will get to know the types of test doubles, Vitest's tools for creating them (vi.fn, vi.spyOn, vi.mock, fake timers), how to wait for promises with flushPromises, how to replace child components with stubs and how to test components that use the router. You will apply all this to RoomDetailView, LoginView, ReceptionClock and the simulated API itself.

Contents

  1. Why isolate dependencies
  2. Test doubles: dummy, stub, spy, mock and fake
  3. vi.fn: mock functions and their assertions
  4. vi.spyOn: spying on and replacing existing methods
  5. vi.mock: mocking entire modules
  6. Cleaning up between tests: mockClear, mockReset and mockRestore
  7. Promises: flushPromises and controlled promises
  8. Fake timers
  9. Component stubs
  10. The router in tests
  11. Case study: RoomDetailView
  12. Case study: LoginView
  13. Mocking the network at the HTTP level: MSW
  14. Try it

  1. Why isolate dependencies

A dependency is anything the code under test uses but does not control. In Colmena there are several kinds, and each one poses a different problem in a test:

Dependency Where it appears Problem in a test
The API (src/api/) Stores, and through them the views Slow (random delay), unpredictable (10% failures), with data that changes (localStorage)
Time (Date, setInterval, setTimeout) ReceptionClock, the room-full notice, the catalogue cache, the API delay The result changes on every run; really waiting would make the tests painfully slow
Chance (Math.random) randomDelay, failSometimes The test passes or fails depending on luck
The browser (window.confirm, localStorage) Cancelling a booking, persistence jsdom does not show dialogs; saved data contaminates other tests
The router LoginView, RoomDetailView, any RouterLink Without a router, useRoute() and useRouter() return nothing
Expensive child components BuildingMap, loaded asynchronously They add work and effects the test does not need

A good test is fast, deterministic (always the same result) and isolated (it does not depend on other tests or on the environment). To achieve this, we replace the problematic dependencies, and only those: anything fast and predictable, such as StatusBadge or formatPlugin, stays real. Each replacement is a small lie the test tells itself, and the more lies there are, the less the test resembles reality.

  1. Test doubles: dummy, stub, spy, mock and fake

Just as a stunt double stands in for the actor in dangerous film scenes, a test double stands in for a real dependency. The classic terminology distinguishes five types according to what they do:

Type What it does What it is for In Colmena
Dummy Nothing: it just fills a gap Filling in a required parameter the test does not use An empty session passed as a prop to BookingForm when it does not matter
Stub Returns prepared answers Controlling what the code under test receives A fetchRooms that always returns the five rooms; RouterLinkStub
Spy Records how it is called (and can let the real call through) Checking what the code does with the dependency Checking that console.log received the mounting message
Mock A stub and a spy at once, with expectations about its calls Checking the interaction: with which arguments and how many times A mocked authenticate: it returns Laura and we check that it received the email without spaces
Fake A real but simplified implementation Replacing something heavy with something light that works Colmena's own simulated API (localStorage as the database), an in-memory router, MSW

In practice, Vitest uses a single tool for almost all of them: the mock function, created with vi.fn or vi.spyOn, which acts as a stub, a spy or a mock depending on how you configure it and what you check. The terminology is still useful for thinking: before replacing something, ask yourself whether you need to control what it returns (stub), check how it is used (spy/mock) or both. And note the last row: Colmena has been working with a fake since module 2. The API in src/api/ does not talk to any server; it imitates one. It is a test double we also use in development.

  1. vi.fn: mock functions and their assertions

vi.fn() creates a function that records every call and returns whatever you tell it to:

import { vi, expect } from 'vitest'

const authenticate = vi.fn() // returns undefined by default

authenticate('[email protected]', 'colmena')

expect(authenticate).toHaveBeenCalledTimes(1)
expect(authenticate).toHaveBeenCalledWith('[email protected]', 'colmena')
expect(authenticate.mock.calls).toEqual([['[email protected]', 'colmena']])

To decide what it returns, chain one of these methods (the Once variant only affects the next call and takes priority):

Method The mock function...
mockReturnValue(value) / mockReturnValueOnce(value) Returns value
mockResolvedValue(value) / mockResolvedValueOnce(value) Returns a promise resolved with value (like a request that works)
mockRejectedValue(error) / mockRejectedValueOnce(error) Returns a promise rejected with error (like a request that fails)
mockImplementation(fn) / mockImplementationOnce(fn) Runs fn with the same arguments and returns its result
const fetchRooms = vi.fn()
  .mockRejectedValueOnce(new Error('No connection')) // 1st call: fails
  .mockResolvedValue([{ id: 'panal' }])               // the following ones: work

await fetchRooms().catch((e) => e.message) // 'No connection'
await fetchRooms()                         // [{ id: 'panal' }]

And to check how it has been used:

Assertion Checks
toHaveBeenCalled() That it has been called at least once
toHaveBeenCalledTimes(n) That it has been called exactly n times
toHaveBeenCalledWith(...args) That some call received those arguments
toHaveBeenLastCalledWith(...args) That the last call received those arguments
toHaveBeenNthCalledWith(n, ...args) That call number n (starting at 1) received those arguments
toHaveReturnedWith(value) That some call returned that value
.not.toHaveBeenCalled() That it has not been called

Inside toHaveBeenCalledWith you can use asymmetric matchers when you are not interested in an exact value: expect.any(String), expect.objectContaining({ roomId: 'polen' }) or expect.stringContaining('Room').

  1. vi.spyOn: spying on and replacing existing methods

vi.fn creates a new function. vi.spyOn(object, 'method') replaces a method that already exists on an object with a mock function. By default it lets the call through to the original method (a pure spy); if you chain mockReturnValue or mockImplementation, it replaces it.

Three uses we will need in Colmena:

// 1. Silence (and check) the console.log calls of ReceptionClock and RoomCard
vi.spyOn(console, 'log').mockImplementation(() => {})
// ... mount ...
expect(console.log).toHaveBeenCalledWith('[ReceptionClock] mounted: timer started')

// 2. Make the simulated API's randomness predictable
vi.spyOn(Math, 'random').mockReturnValue(0.5) // a 900 ms delay and no failure (0.5 ≥ 0.1)

// 3. Answer the confirmation dialog, which jsdom cannot show
vi.spyOn(window, 'confirm').mockReturnValue(true) // the user clicks "OK"

The third case deserves an explanation: jsdom does not implement dialogs, so window.confirm only writes a "not implemented" warning and returns undefined, which the code would interpret as "Cancel". Replacing it is the only way to test what happens when the user confirms.

Whatever is replaced with spyOn must be restored at the end of the test, because it modifies a global object shared by all the tests in the file. We will see how in section 6.

  1. vi.mock: mocking entire modules

5.1 Why mock a module

Colmena's stores do not receive the API as a parameter: they import it (import { api } from '@/api'). For them to use a mocked API in a test, you have to replace the module they import. That is what vi.mock does.

In Advanced Vuex Patterns we created the src/api/index.js facade, which gathers the whole data layer into a single api object. Now its usefulness becomes clear: mocking one module, @/api, is enough to ensure that no store ever reaches the real API.

5.2 Automatic mocking

import { vi } from 'vitest'
import { api } from '@/api'

// Replaces the module in the WHOLE test file
vi.mock('@/api')

// now api.rooms.fetchRooms, api.bookings.createBooking, api.session.authenticate...
// are mock functions that return undefined
vi.mocked(api.rooms.fetchRooms).mockResolvedValue([{ id: 'panal', name: 'Panal Room' /* ... */ }])
  • vi.mock(path) with no further arguments generates an automatic mock: Vitest examines the real module's exports and creates a copy with the same shape in which every function is a vi.fn(). As api is an object containing objects with functions, all of them end up mocked.
  • The path is resolved like an import: '@/api' points to src/api/index.js, the same file the stores import. That is why the replacement affects them.
  • vi.mock is hoisted: even if you write it below the imports, Vitest moves it to the top of the file, so that it is applied before any module is loaded. The test's import { api } therefore receives the mocked version: the same one the stores will receive.
  • vi.mocked(fn) does nothing at runtime; it only tells the editor that fn is a mock function, so that it offers you mockResolvedValue and company when autocompleting. With TypeScript (09-02) it will be essential; in JavaScript it is an aid to readability.

5.3 Mocking with a factory

If you want to decide the module's shape yourself, pass a factory as the second argument:

// The factory returns the exports of the mocked module
const authenticate = vi.hoisted(() => vi.fn())

vi.mock('@/api', () => ({
  api: {
    session: { authenticate },
    bookings: { fetchBookings: vi.fn().mockResolvedValue([]) },
    rooms: { fetchRooms: vi.fn().mockResolvedValue([]) }
  }
}))
  • The factory runs before the rest of the file (because of hoisting), so it cannot use variables declared above it in the usual way: they would not have been initialised yet. vi.hoisted declares a variable that is also hoisted, and which the factory can use.
  • With a factory, anything you do not declare does not exist: if a store called api.bookings.createBooking, it would fail with "is not a function". Automatic mocking does not have that problem, which is why it is the one we will use almost always.
  • A third variant, useful when you only want to replace part of a module, is to start from the original: vi.mock(path, async (importOriginal) => ({ ...(await importOriginal()), someFunction: vi.fn() })).

  1. Cleaning up between tests: mockClear, mockReset and mockRestore

Mock functions accumulate state: the recorded calls and the configured values. If one test configures mockRejectedValue and the next does not change it, the second will inherit the failure. There are three levels of cleaning up:

Method Clears the recorded calls Clears the configured values (mockReturnValue...) Restores the original method (spyOn)
fn.mockClear() Yes No No
fn.mockReset() Yes Yes: it goes back to the implementation it was created with (vi.fn(impl)), or to returning undefined No
fn.mockRestore() Yes Yes Yes, if it was created with vi.spyOn

Each one has a version for all mock functions at once: vi.clearAllMocks(), vi.resetAllMocks() and vi.restoreAllMocks(). The usual pattern is:

import { beforeEach, afterEach, vi } from 'vitest'

beforeEach(() => {
  vi.resetAllMocks() // each test starts with the module's mocks empty
})

afterEach(() => {
  vi.restoreAllMocks() // console.log, Math.random, window.confirm... are the real ones again
})
  • beforeEach(fn) runs fn before each test in the describe (or in the file, if it is outside any describe); afterEach(fn), after each one. There are also beforeAll and afterAll, which run only once.
  • vi.restoreAllMocks() only affects what was created with vi.spyOn: the functions of a module mocked with vi.mock stay mocked, which is what we want.
  • If you prefer not to repeat it in every file, Vitest has equivalent configuration options in test (clearMocks, mockReset, restoreMocks). Writing it explicitly has the advantage that it can be read in the test itself.

  1. Promises: flushPromises and controlled promises

When a component requests data on mounting, the response arrives afterwards, even if the mocked API responds instantly: a resolved promise runs its then callbacks in the microtask queue, and between that response and the updated DOM there are several steps (the await in the store's action, the assignment of the state, Vue's rendering). nextTick only waits for the next render; to wait for all pending promises, Vue Test Utils offers flushPromises:

import { flushPromises } from '@vue/test-utils'

vi.mocked(api.rooms.fetchRooms).mockResolvedValue(rooms)
const wrapper = mountWithPlugins(RoomDetailView, { /* ... */ })

await flushPromises() // pending promises are resolved and Vue updates the DOM

expect(wrapper.get('h2').text()).toBe('Néctar Room')

There is a less obvious consequence: with mockResolvedValue, the response arrives so soon that it is hard to see the intermediate loading state. All it takes is for the test to do any await (mounting after preparing the router, for example) and, by the time it looks, the data has already been rendered. To test the loading state you need to control when the promise resolves. Promise.withResolvers() (available since Node 22) creates a promise together with its resolve and reject functions:

const { promise, resolve, reject } = Promise.withResolvers()
vi.mocked(api.rooms.fetchRooms).mockReturnValue(promise) // the API "keeps thinking"

// ... mount, check "Loading the room…" ...

resolve(rooms)          // now the response arrives (or reject(error) for a failure)
await flushPromises()

In earlier versions of Node the same is achieved with let resolve; const promise = new Promise((r) => (resolve = r)).

  1. Fake timers

8.1 Controlling the clock

Vitest can replace setTimeout, setInterval, Date and company with fake versions that do not move forward on their own: time only passes when the test says so.

Function What it does
vi.useFakeTimers() Enables the fake timers (including Date)
vi.setSystemTime(date) Sets the "current" date and time (new Date(), Date.now())
vi.advanceTimersByTime(ms) Moves the clock forward ms milliseconds and runs the timers that fall due
vi.advanceTimersByTimeAsync(ms) The same, but it lets promises resolve between one timer and the next
vi.runAllTimers() / vi.runAllTimersAsync() Runs all pending timers, until there are none left
vi.getTimerCount() How many timers are pending
vi.useRealTimers() Goes back to the real timers

8.2 ReceptionClock

The reception clock from 01-04 keeps a Date in now, refreshes it every second with setInterval and, since 07-02, displays it with $format.time(now, { seconds: true }). Create src/components/__tests__/ReceptionClock.spec.js:

// src/components/__tests__/ReceptionClock.spec.js
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { nextTick } from 'vue'
import { mountWithPlugins } from '@tests/mount.js'
import ReceptionClock from '../ReceptionClock.vue'

describe('ReceptionClock', () => {
  beforeEach(() => {
    vi.useFakeTimers()
    vi.setSystemTime(new Date(2026, 10, 3, 9, 30, 0)) // 3 November 2026, 09:30:00
    vi.spyOn(console, 'log').mockImplementation(() => {})
  })

  afterEach(() => {
    vi.useRealTimers()
    vi.restoreAllMocks()
  })

  it('shows the current time and updates it every second', async () => {
    const wrapper = mountWithPlugins(ReceptionClock)
    expect(wrapper.text()).toContain('09:30:00')

    vi.advanceTimersByTime(1000)
    await nextTick()
    expect(wrapper.text()).toContain('09:30:01')

    vi.advanceTimersByTime(59_000)
    await nextTick()
    expect(wrapper.text()).toContain('09:31:00')
  })

  it('stops its timer when unmounted', () => {
    const wrapper = mountWithPlugins(ReceptionClock)
    expect(vi.getTimerCount()).toBe(1)

    wrapper.unmount()

    expect(vi.getTimerCount()).toBe(0)
    expect(console.log).toHaveBeenCalledWith('[ReceptionClock] unmounted: timer stopped')
  })
})
  • new Date(2026, 10, 3, 9, 30, 0) uses local time (and remember: months start at 0, so 10 is November). As format.time also works in local time, the test shows "09:30:00" in any time zone.
  • advanceTimersByTime(1000) runs the setInterval once; with the fake timers, new Date() inside updateTime already returns 09:30:01. Afterwards, nextTick is needed for Vue to render the change.
  • 59_000: the underscore is a JavaScript numeric separator, just to make it easier to read. In a test we move forward a whole minute in microseconds of real time.
  • The second test guards against the memory leak we studied in 01-04: if someone deletes the clearInterval from onUnmounted, getTimerCount() will stay at 1 and the test will fail.
  • The console.log spy silences the mounting and unmounting messages and, while it is at it, lets us check them.
  • afterEach brings back the real timers: leaving them fake would affect other files running in the same process.

The same control over the clock solves the problem we left pending in RoomCard: the exact time in the room-full notice.

// In RoomCard.spec.js: add vi and afterEach to the vitest import, and inside the describe:
afterEach(() => {
  vi.useRealTimers() // harmless if the test did not enable them
})

it('states the exact time at which the room filled up', async () => {
  vi.useFakeTimers()
  vi.setSystemTime(new Date(2026, 10, 3, 10, 32, 5))
  const room = createRoom({ id: 'celda', name: 'Celda Booth', capacity: 1 })
  const wrapper = mountWithPlugins(RoomCard, { props: { room } })

  await button(wrapper, '+ Attendee').trigger('click')

  expect(wrapper.get('.notice').text()).toBe('Room full as of 10:32:05!')
})

Restoring the timers in afterEach, and not on the last line of the test, guarantees that they are restored even if the test fails: a failed assertion throws an error and the following lines never get to run.

8.3 The simulated API's delay

The simulated API combines time and chance: randomDelay() uses Math.random to decide how long to wait and failSometimes() uses it to decide whether to fail. By controlling both, we can test the simulation itself deterministically. Create src/api/__tests__/rooms.spec.js:

// src/api/__tests__/rooms.spec.js
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { fetchRooms, fetchRoom } from '@/api/rooms.js'

describe('simulated rooms API', () => {
  beforeEach(() => {
    vi.useFakeTimers()
  })

  afterEach(() => {
    vi.useRealTimers()
    vi.restoreAllMocks()
  })

  it('responds after the delay with the rooms on the requested floor', async () => {
    vi.spyOn(Math, 'random').mockReturnValue(0.5) // delay: 300 + 0.5 × 1200 = 900 ms; does not fail
    let resolved = false
    const promise = fetchRooms({ floor: 1 })
    promise.then(() => (resolved = true))

    await vi.advanceTimersByTimeAsync(899)
    expect(resolved).toBe(false) // the delay has not passed yet

    await vi.advanceTimersByTimeAsync(1)
    await expect(promise).resolves.toHaveLength(2) // Panal Room and Polen Room
  })

  it('fails like a server that is down when chance decides so', async () => {
    vi.spyOn(Math, 'random').mockReturnValue(0.05) // 0.05 < 0.1: this request fails
    const promise = fetchRoom('panal')
    const assertion = expect(promise).rejects.toMatchObject({ status: 503, code: 'connection' })

    await vi.runAllTimersAsync()

    await assertion
  })

  it('can be cancelled before it responds', async () => {
    const controller = new AbortController()
    const promise = fetchRooms({}, { signal: controller.signal })

    controller.abort()

    await expect(promise).rejects.toMatchObject({ name: 'AbortError' })
    expect(vi.getTimerCount()).toBe(0) // wait() has cleared its setTimeout
  })
})
  • advanceTimersByTimeAsync (with Async): fetchRooms does await wait(...) and then carries on running. The asynchronous version lets those promises progress between one timer and the next; with the synchronous version, the setTimeout would fall due but the rest of the function would not get to run before the assertion.
  • .resolves and .rejects wait for the promise to settle and apply the matcher to its value or to its error. They take await in front.
  • Why assertion is created before moving the clock forward: the promise will be rejected while the timers are advancing. If nobody were listening to it at that moment, Node would warn about an unhandled rejection. By creating the expectation first, the rejection already has someone to pick it up.
  • toMatchObject checks that the error has at least those properties (status, code), the ones we added with errorWithStatus in 07-03.
  • The third test protects the cancellation from 02-05: an AbortError and no orphaned timer.

  1. Component stubs

A component stub replaces a child component with a simpler one. Stubs are configured with global.stubs:

Value Result Example
true An empty <name-stub> element with the props as attributes stubs: { BuildingMap: true }
A component That component instead of the real one stubs: { RouterLink: RouterLinkStub }
false Disables a stub (useful with shallowMount) stubs: { StatusBadge: false }

When is it worth it? When the child is expensive, has effects the test does not want to trigger or depends on something that is not available. In Colmena, the typical case is BuildingMap: it is loaded with defineAsyncComponent (03-06), which means a dynamic import, a loading component, an error component and a large SVG. If you were testing RoomsView by switching to the map view, you would not want to check the drawing of the building, but that the right view is chosen:

// Sketch: testing the catalogue's view choice without the real map
const wrapper = mountWithPlugins(RoomsView, {
  router,
  global: {
    plugins: [createPinia()],
    stubs: { BuildingMap: true }
  }
})
// ... click the map view button ...
expect(wrapper.findComponent({ name: 'BuildingMap' }).exists()).toBe(true)

The stub keeps the component's name, so findComponent({ name: ... }) finds it and you can check its props. You already know another stub: RouterLinkStub, which mountWithPlugins puts in place of RouterLink when there is no router. It renders as an <a> without an href and keeps the to prop for you to check, but it does not navigate.

A warning: by default, stubs do not render the content of their slots. If the replaced child receives text through a slot (as BaseButton does), that text disappears from the test. It is what you saw with shallowMount, which is nothing more than "mounting with every child replaced by a stub". Use stubs one at a time and for a reason.

  1. The router in tests

10.1 Two strategies

A component that uses useRoute(), useRouter() or RouterLink needs a router. There are two ways of giving it one:

Real in-memory router Mocking vue-router with vi.mock
How createRouter with createMemoryHistory and some test routes, installed with global.plugins vi.mock('vue-router') and useRoute/useRouter returning mock objects
RouterLink Works for real: it generates the href and navigates when clicked Has to be replaced (RouterLinkStub)
What the test checks Where the user ends up: router.currentRoute.value.fullPath What was called: expect(replace).toHaveBeenCalledWith(...)
If you change push to replace, or an object to a string The test still passes if the destination is the same The test fails, even though the user notices nothing
Preparation Somewhat more (test routes, isReady) Minimal
When to use it By default: views that read the route, navigate or contain links To isolate a component that only calls one router function, or when mounting a real one would be overkill

In-memory history is what we anticipated in 04-01: createMemoryHistory keeps the entries in an array, without touching the address bar, so each test can start with a clean history.

10.2 tests/router.js

Create a second helper in tests/:

// tests/router.js
// Router for tests: in-memory history and Colmena's named routes,
// all with an empty component. The view under test is mounted separately.
import { h } from 'vue'
import { createRouter, createMemoryHistory } from 'vue-router'

const Empty = { render: () => h('div') }

const ROUTES = [
  ['home', '/'],
  ['rooms', '/rooms'],
  ['room-detail', '/rooms/:id'],
  ['book', '/book/:roomId'],
  ['dashboard', '/dashboard'],
  ['dashboard-profile', '/dashboard/profile'],
  ['dashboard-bookings', '/dashboard/bookings'],
  ['login', '/login']
]

export async function createTestRouter(initialRoute = '/') {
  const router = createRouter({
    history: createMemoryHistory(),
    routes: ROUTES.map(([name, path]) => ({ name, path, component: Empty }))
  })
  router.push(initialRoute)
  await router.isReady() // the first navigation is asynchronous (04-02)
  return router
}

The decisions:

  • The same named routes as src/router/index.js (room-detail, book, dashboard-bookings...), so that the views' RouterLinks and router.push({ name }) calls resolve just as they do in the application. If a view links to a name that is not on the list, Vue Router will throw a clear error: add it.
  • One empty component for all of them: the view we are testing is not rendered through <RouterView>; we mount it ourselves. The router only has to know the addresses. Empty uses a render function (h('div')) instead of template, because the build of Vue used with Vite does not include the runtime template compiler.
  • A new router on every call: a router's state (its current route, its history) must not carry over from one test to another.
  • Why not use src/router/index.js? Because it creates the router with createWebHistory and adds the guards, which query the stores. To test a view, those are extra dependencies; the guards have their place in the end-to-end tests (08-04). If you wanted to unit test them, the way to do it would be to export routes and the guard functions from the router file.
  • await router.isReady(): the initial navigation is asynchronous, as we saw in 04-02. If you mount the view earlier, useRoute() will return the empty initial route (/) instead of the one you asked for.

10.3 mountWithPlugins accepts a router

Update tests/mount.js so that it accepts the router option. If the test passes a router, it is installed and RouterLink is no longer replaced; if not, everything stays as in the previous lesson:

// tests/mount.js: replaces mountWithPlugins
export function mountWithPlugins(component, { router, global = {}, ...rest } = {}) {
  return mount(component, {
    ...rest,
    global: {
      ...global,
      plugins: [
        i18n,
        [formatPlugin, { locale: 'en-GB', currency: 'EUR' }],
        directivesPlugin,
        FloatingVue,
        ...(global.plugins ?? []), // Pinia, if the test passes it...
        ...(router ? [router] : []) // ...and the router afterwards, as in main.js
      ],
      provide: { [CONFIG_KEY]: TEST_CONFIG, ...global.provide },
      // With a router, RouterLink is the real one; without one, VTU's substitute
      stubs: { ...(router ? {} : { RouterLink: RouterLinkStub }), ...global.stubs }
    }
  })
}
  • router is extracted from the options with destructuring, because it is not a mount option: the rest (props, slots, attachTo...) is still passed through as it is.
  • The router goes at the end of the plugin list, after the ones the test passes: in main.js, Pinia is installed before the router because the guards use stores (05-07). The test router has no guards, but keeping the order avoids surprises the day it does.
  • The tests from the previous lesson do not change: they do not pass router, so they still receive RouterLinkStub.

  1. Case study: RoomDetailView

11.1 What needs testing

Since Pinia, a room's spec sheet does not request the room from the API; instead it calls roomsStore.loadRooms() and looks the room up in the store's catalogue. Its states are:

stateDiagram-v2
    [*] --> Loading: mounts (loadRooms)
    Loading --> Data: the room is in the catalogue
    Loading --> NotFound: catalogue loaded, the room does not exist
    Loading --> Error: the API fails
    Error --> Loading: Retry (loadRooms force)

The test will be an integration test: the real view, with the real Pinia store and its real child components (BasePanel, StatusBadge, BaseButton, NotFoundView), and only two doubles: the API (mocked with vi.mock) and the router (real, in memory). That way we genuinely check that the view and the store fit together, and not just each one on its own.

11.2 The tests

Create src/views/__tests__/RoomDetailView.spec.js:

// src/views/__tests__/RoomDetailView.spec.js
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { flushPromises } from '@vue/test-utils'
import { createPinia } from 'pinia'
import { api } from '@/api'
import { errorWithStatus } from '@/api/simulation.js'
import { rooms } from '@/data/rooms.js'
import { mountWithPlugins } from '@tests/mount.js'
import { createTestRouter } from '@tests/router.js'
import RoomDetailView from '../RoomDetailView.vue'

vi.mock('@/api')

// Mounts the spec sheet as the router would show it at /rooms/:id
async function mountSpecSheet(id) {
  const router = await createTestRouter(`/rooms/${id}`)
  const wrapper = mountWithPlugins(RoomDetailView, {
    props: { id },
    router,
    global: { plugins: [createPinia()] } // a new Pinia: no store shares state with another test
  })
  return { wrapper, router }
}

function button(wrapper, text) {
  return wrapper.findAll('button').find((b) => b.text().includes(text))
}

describe('RoomDetailView', () => {
  beforeEach(() => {
    vi.resetAllMocks()
  })

  it('shows "Loading" and then the room spec sheet', async () => {
    const { promise, resolve } = Promise.withResolvers()
    vi.mocked(api.rooms.fetchRooms).mockReturnValue(promise)

    const { wrapper } = await mountSpecSheet('nectar')
    await flushPromises()
    expect(wrapper.text()).toContain('Loading the room…')

    resolve(structuredClone(rooms))
    await flushPromises()

    expect(wrapper.text()).not.toContain('Loading the room…')
    expect(wrapper.get('h2').text()).toBe('Néctar Room')
    expect(wrapper.text()).toContain('12 people')
    expect(document.title).toBe('Néctar Room · Colmena Bookings')
    expect(api.rooms.fetchRooms).toHaveBeenCalledTimes(1)
  })

  it('shows the error and lets the user retry', async () => {
    vi.mocked(api.rooms.fetchRooms)
      .mockRejectedValueOnce(errorWithStatus('Could not connect to the Colmena server', 503, 'connection'))
      .mockResolvedValueOnce(structuredClone(rooms))

    const { wrapper } = await mountSpecSheet('polen')
    await flushPromises()
    expect(wrapper.get('[role="alert"]').text()).toContain('Could not connect')

    await button(wrapper, 'Retry').trigger('click')
    await flushPromises()

    expect(wrapper.find('[role="alert"]').exists()).toBe(false)
    expect(wrapper.get('h2').text()).toBe('Polen Room')
    expect(api.rooms.fetchRooms).toHaveBeenCalledTimes(2)
  })

  it('shows the not-found page if the room does not exist', async () => {
    vi.mocked(api.rooms.fetchRooms).mockResolvedValue(structuredClone(rooms))

    const { wrapper, router } = await mountSpecSheet('basement')
    await flushPromises()

    expect(wrapper.text()).toContain('This page does not exist')
    expect(router.currentRoute.value.fullPath).toBe('/rooms/basement') // the URL is kept
  })

  it('"Back" leads to the catalogue if the spec sheet was opened directly', async () => {
    vi.mocked(api.rooms.fetchRooms).mockResolvedValue(structuredClone(rooms))
    const { wrapper, router } = await mountSpecSheet('panal')
    await flushPromises()

    await button(wrapper, 'Back').trigger('click')
    await flushPromises()

    expect(router.currentRoute.value.name).toBe('rooms')
  })
})

Let's analyse the decisions:

  • vi.mock('@/api') at the top: the useRoomsStore store imports api from @/api and receives the mock. The view and the store are the real ones; the only thing that changes is where the data comes from.
  • createPinia() on every mount: the store is created inside the test application and dies with it. If two tests shared a Pinia, the five-minute cache of loadRooms would mean the second one requested nothing from the API.
  • structuredClone(rooms): the test data is the data in src/data/rooms.js, but copied, as the real API does. If the view or the store modified the object, they would not contaminate the data module that all the tests share.
  • The loading state with a controlled promise (section 7): the API "keeps thinking" until we call resolve. The first flushPromises ensures that the view has reached the loading state; the second, that it has rendered the data.
  • mockRejectedValueOnce(...).mockResolvedValueOnce(...) describes a sequence: the first request fails and the second works. The error is created with errorWithStatus, the same function the real API uses, so it has exactly the same shape.
  • toContain('Could not connect'): we check a fragment, not the complete text, because the view shows it with or without the final full stop depending on whether the store keeps the error's message or the whole error in order to translate it (the change we proposed at the end of 07-03).
  • The non-existent room checks two things: that NotFoundView is rendered and that the URL does not change, the decision made in 04-03.
  • "Back" with a real router: as the spec sheet was opened directly, there is no history.state.back and goBack() does a push to the catalogue. We check where the user ends up (currentRoute), not which function was called.

  1. Case study: LoginView

12.1 With the in-memory router

LoginView is the view to which the global guard sends anyone without a session, with the requested route in ?redirect=. After signing in, destinationAfterLogin() returns that route if it is internal and submit() navigates with replace. Create src/views/__tests__/LoginView.spec.js:

// src/views/__tests__/LoginView.spec.js
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { flushPromises } from '@vue/test-utils'
import { createPinia } from 'pinia'
import { api } from '@/api'
import { errorWithStatus } from '@/api/simulation.js'
import { mountWithPlugins } from '@tests/mount.js'
import { createTestRouter } from '@tests/router.js'
import LoginView from '../LoginView.vue'

vi.mock('@/api')

const LAURA = { name: 'Laura Gómez', email: '[email protected]', plan: 'flexible', role: 'member' }

async function mountLogin(initialRoute) {
  const router = await createTestRouter(initialRoute)
  const wrapper = mountWithPlugins(LoginView, {
    router,
    global: { plugins: [createPinia()] },
    attachTo: document.body // to check the focus set by v-focus
  })
  return { wrapper, router }
}

async function signInWith(wrapper, email, password) {
  await wrapper.get('input[type="email"]').setValue(email)
  await wrapper.get('input[type="password"]').setValue(password)
  await wrapper.get('form').trigger('submit')
  await flushPromises()
}

describe('LoginView', () => {
  beforeEach(() => {
    vi.resetAllMocks()
    // signIn loads the bookings (and the catalogue) in the background
    vi.mocked(api.bookings.fetchBookings).mockResolvedValue([])
    vi.mocked(api.rooms.fetchRooms).mockResolvedValue([])
  })

  it('returns to the requested route after signing in', async () => {
    vi.mocked(api.session.authenticate).mockResolvedValue({ ...LAURA })
    const { wrapper, router } = await mountLogin({
      name: 'login',
      query: { redirect: '/book/polen?attendees=3' }
    })

    expect(wrapper.text()).toContain('Sign in to continue.')
    expect(document.activeElement).toBe(wrapper.get('input[type="email"]').element)

    await signInWith(wrapper, '  [email protected] ', 'colmena')

    expect(api.session.authenticate).toHaveBeenCalledWith('[email protected]', 'colmena')
    expect(router.currentRoute.value.fullPath).toBe('/book/polen?attendees=3')
    wrapper.unmount()
  })

  it('goes to the dashboard if there is no redirect', async () => {
    vi.mocked(api.session.authenticate).mockResolvedValue({ ...LAURA })
    const { wrapper, router } = await mountLogin('/login')

    await signInWith(wrapper, '[email protected]', 'colmena')

    expect(router.currentRoute.value.name).toBe('dashboard')
    wrapper.unmount()
  })

  it('ignores a redirect to another website', async () => {
    vi.mocked(api.session.authenticate).mockResolvedValue({ ...LAURA })
    const { wrapper, router } = await mountLogin('/login?redirect=//malicious-site.example')

    await signInWith(wrapper, '[email protected]', 'colmena')

    expect(router.currentRoute.value.name).toBe('dashboard')
    wrapper.unmount()
  })

  it('shows the translated error if the credentials are not valid', async () => {
    vi.mocked(api.session.authenticate).mockRejectedValue(
      errorWithStatus('Incorrect email or password', 401, 'credentials')
    )
    const { wrapper, router } = await mountLogin('/login')

    await signInWith(wrapper, '[email protected]', 'bee')

    expect(wrapper.get('[role="alert"]').text()).toBe('Incorrect email or password.')
    expect(router.currentRoute.value.name).toBe('login')
    wrapper.unmount()
  })
})

The most relevant points:

  • The initial route as an object ({ name: 'login', query: { redirect: ... } }): the router encodes the query, just as the global guard does when it builds the redirect. We check the complete destination, with its own query (?attendees=3), which is exactly what 04-06 promised to keep.
  • We find the fields by their type (input[type="email"]), which is what TextField forwards to the <input>. We do not depend on the labels, which could be translated.
  • The email with spaces: v-model.trim must clean it up before it reaches the API. The toHaveBeenCalledWith assertion protects that detail.
  • The initial focus checks that v-focus (installed by directivesPlugin in the helper) works in the view. That is why we mount with attachTo and unmount at the end of each test.
  • The malicious redirect protects the security rule in destinationAfterLogin(): internal routes only. It is the kind of check nobody repeats by hand, and which a test keeps an eye on for ever.
  • The credentials error runs through the whole chain from 07-03: the API throws an error with the code credentials, the store lets it through, the view stores it and translateError turns it into the message in en.json.

12.2 The alternative: mocking vue-router

For comparison, this is what the first test would look like mocking the router instead of using a real one (in a separate file, because vi.mock affects the whole file):

// src/views/__tests__/LoginView.mocked.spec.js
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { flushPromises } from '@vue/test-utils'
import { createPinia } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { api } from '@/api'
import { mountWithPlugins } from '@tests/mount.js'
import LoginView from '../LoginView.vue'

vi.mock('@/api')
vi.mock('vue-router', () => ({
  useRoute: vi.fn(),
  useRouter: vi.fn()
}))

describe('LoginView (mocked router)', () => {
  const replace = vi.fn()

  beforeEach(() => {
    vi.resetAllMocks()
    vi.mocked(useRoute).mockReturnValue({ query: { redirect: '/dashboard/bookings' } })
    vi.mocked(useRouter).mockReturnValue({ replace })
    vi.mocked(api.session.authenticate).mockResolvedValue({
      name: 'Laura Gómez', email: '[email protected]', plan: 'flexible', role: 'member'
    })
    vi.mocked(api.bookings.fetchBookings).mockResolvedValue([])
    vi.mocked(api.rooms.fetchRooms).mockResolvedValue([])
  })

  it('asks the router to go to the redirect route', async () => {
    const wrapper = mountWithPlugins(LoginView, { global: { plugins: [createPinia()] } })

    await wrapper.get('input[type="email"]').setValue('[email protected]')
    await wrapper.get('input[type="password"]').setValue('colmena')
    await wrapper.get('form').trigger('submit')
    await flushPromises()

    expect(replace).toHaveBeenCalledWith('/dashboard/bookings')
  })
})

It is shorter, but compare it with the real-router test: this test knows that the view uses replace and that it passes it a string. If tomorrow someone changes it to router.replace({ path: destination }), the user will notice nothing and this test will fail. The real-router test checks the result and survives the change. It is the table in section 10.1 in action.

  1. Mocking the network at the HTTP level: MSW

Colmena mocks the network inside the application: src/api/ imitates a server and never makes a real request. The day Colmena has a real server, src/api/rooms.js will use fetch, and the most faithful way of testing it will be to intercept the HTTP requests beneath the application, without touching its code. That is what Mock Service Worker (MSW) does: it defines handlers for HTTP addresses and methods and responds to the requests that match, both in Node (the tests) and in the browser (development).

// Sketch for when src/api/ uses fetch against a real server
import { beforeAll, afterEach, afterAll } from 'vitest'
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'

const server = setupServer(
  http.get('https://api.colmena.example/rooms', () => HttpResponse.json(rooms))
)

beforeAll(() => server.listen({ onUnhandledRequest: 'error' })) // fails on unexpected requests
afterEach(() => server.resetHandlers())                         // undoes each test's changes
afterAll(() => server.close())

// In a specific test, the server "goes down":
// server.use(http.get('https://api.colmena.example/rooms', () => new HttpResponse(null, { status: 503 })))
vi.mock('@/api') MSW
What it replaces The data layer module The network, beneath fetch
What is left untested The src/api/ layer itself (building URLs, headers, converting responses) None of the application's code
Needs Nothing else A dependency and some configuration
Fits Colmena today Yes: there are no HTTP requests When there is a real server

  1. Try it

  1. All green. Run npm test: ReceptionClock, the rooms API, RoomDetailView and LoginView join the tests from the previous lesson. Look at the total time: even though the simulated API takes up to 1.5 seconds per request and the clock moves forward a minute, everything finishes in a couple of seconds.
  2. Without fake timers. In ReceptionClock.spec.js, comment out vi.useFakeTimers() and vi.setSystemTime(...). The first test fails: the time is the real one and the clock does not move forward. Restore it.
  3. The leak, detected. In ReceptionClock.vue, comment out the clearInterval in onUnmounted: the second test fails with expected 1 to be 0. Restore it.
  4. An inherited mock. In RoomDetailView.spec.js, comment out the vi.resetAllMocks() in the beforeEach and move the error test to the beginning of the describe. Run the tests: depending on the order, a test may receive responses configured by another one. Restore it and remember why that beforeEach exists.
  5. The security rule. In LoginView.vue, remove the !destination.startsWith('//') condition from destinationAfterLogin: the malicious redirect test fails. Restore it.
  6. The real router versus the mocked one. In LoginView.vue, change router.replace(destinationAfterLogin()) to router.push(destinationAfterLogin()). The test with the real router still passes; the mocked one fails. Which of the two got it right? (For the user, the difference is that the Back button would return to the login page; if that matters, the real test should check it with router.back().) Restore it.

Common Mistakes and Tips

  • Mocking too much. Each double takes the test further from reality. Replace what is slow, unpredictable and external; leave everything else real (stores, child components, plugins).
  • Not cleaning up the mocks. Configurations and recorded calls carry over from one test to another. vi.resetAllMocks() in beforeEach and vi.restoreAllMocks() in afterEach.
  • Using ordinary variables inside the vi.mock factory. The factory runs before the rest of the file: use vi.hoisted or automatic mocking.
  • Writing vi.mock(...) with a comment on the same line. Vitest moves that call to the top of the file, and some versions get confused by whatever accompanies it and produce a baffling syntax error. Write each vi.mock on its own line, with any comments above it.
  • Forgetting flushPromises after an asynchronous action. nextTick waits for a render, not for the API. If the test does not see the data, a flushPromises is missing.
  • Using advanceTimersByTime with code that does await between timers. Use the Async version, or the code after the await will never get to run.
  • Leaving the fake timers active. Call vi.useRealTimers() in afterEach.
  • Mounting the view before router.isReady(). useRoute() will see the empty initial route and the query will not exist.
  • Sharing a Pinia between tests. The store's cache and state carry over. A new createPinia() on every mount.
  • Checking calls instead of results when the result is observable. If you can check where the user ends up or what they see, do so: the test will survive internal changes.
  • Tip: when an asynchronous test fails intermittently, suspect a promise that is not awaited or an inherited mock. Run the file several times in a row and in a different order (vitest --sequence.shuffle) to unmask it.

Exercises

Exercise 1. Add a test to RoomDetailView.spec.js for the Enjambre Auditorium, which is under maintenance: it must show "Under maintenance: not accepting bookings." and not offer the "Book this room" link. Also check that the "Other rooms" navigation has four links and that, when the Polen Room one is clicked, the router reaches /rooms/polen.

Exercise 2. Write src/api/__tests__/bookings.spec.js for the simulated bookings API from 05-02. With fake timers and a controlled Math.random, check that: (a) createBooking returns the booking with an id assigned by the server (a UUID) and the status confirmed, and that fetchBookings then includes it; (b) a second booking for the same room and day with an overlapping time slot is rejected with status 409, the code overlap and the details of the conflict; (c) a booking whose end time is earlier than its start time is rejected with 422. Make sure each test starts with an empty "database".

Exercise 3. While the password is being checked, the LoginView button shows "Signing in…" and is disabled (to prevent double submissions). Write a test that checks this and then verifies that, once authentication completes, the user reaches the dashboard.

Solutions

Solution 1.

// In RoomDetailView.spec.js, inside the describe
it('explains that a room under maintenance does not accept bookings', async () => {
  vi.mocked(api.rooms.fetchRooms).mockResolvedValue(structuredClone(rooms))
  const { wrapper, router } = await mountSpecSheet('enjambre')
  await flushPromises()

  expect(wrapper.text()).toContain('Under maintenance: not accepting bookings.')
  expect(wrapper.text()).not.toContain('Book this room')

  const others = wrapper.findAll('nav[aria-label="Other rooms"] a')
  expect(others).toHaveLength(4)

  await wrapper.get('nav[aria-label="Other rooms"] a[href="/rooms/polen"]').trigger('click')
  await flushPromises()

  expect(router.currentRoute.value.fullPath).toBe('/rooms/polen')
})
  • nav[aria-label="Other rooms"] locates the navigation by its accessible name, which distinguishes it from any other <nav> on the page.
  • a[href="/rooms/polen"]: with a real router, RouterLink generates the href, so we can find the link by its destination. With RouterLinkStub there would be no href.
  • The click really navigates: RouterLink intercepts the click and calls router.push. After flushPromises, the current route is Polen's. In the application, the view would be reused with the new id; here we have mounted it by hand, so we only check the navigation.

Solution 2.

// src/api/__tests__/bookings.spec.js
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { createBooking, fetchBookings } from '@/api/bookings.js'

function bookingData(changes = {}) {
  return {
    roomId: 'polen', date: '2026-11-03', startTime: '10:00', endTime: '12:00',
    member: 'Laura Gómez', attendees: 3, ...changes
  }
}

describe('simulated bookings API', () => {
  beforeEach(() => {
    localStorage.setItem('colmena-api-bookings', '[]') // an empty "database", without the demo bookings
    vi.useFakeTimers()
    vi.spyOn(Math, 'random').mockReturnValue(0.5) // fixed delay and no connection failures
  })

  afterEach(() => {
    vi.useRealTimers()
    vi.restoreAllMocks()
    localStorage.clear()
  })

  // Lets the simulated delay pass and returns the result of the request
  async function complete(promise) {
    await vi.runAllTimersAsync()
    return promise
  }

  it('creates the booking with a server id and saves it', async () => {
    const created = await complete(createBooking(bookingData({ id: 'client-id' })))

    expect(created.id).toMatch(/^[0-9a-f-]{36}$/)
    expect(created.id).not.toBe('client-id')
    expect(created.status).toBe('confirmed')
    await expect(complete(fetchBookings())).resolves.toEqual([created])
  })

  it('rejects with 409 a booking that overlaps another one', async () => {
    await complete(createBooking(bookingData()))

    const second = createBooking(bookingData({ startTime: '11:00', endTime: '13:00' }))
    const assertion = expect(second).rejects.toMatchObject({
      status: 409,
      code: 'overlap',
      data: { room: 'Polen Room', date: '2026-11-03', start: '10:00', end: '12:00' }
    })
    await vi.runAllTimersAsync()
    await assertion
  })

  it('rejects an invalid time slot with 422', async () => {
    const promise = createBooking(bookingData({ startTime: '12:00', endTime: '10:00' }))
    const assertion = expect(promise).rejects.toMatchObject({ status: 422, code: 'invalidTimeSlot' })
    await vi.runAllTimersAsync()
    await assertion
  })
})
  • '[]' in colmena-api-bookings: readTable() accepts any saved array, so an empty array prevents the demo bookings from being generated and leaves the table under the test's control. localStorage.clear() in afterEach leaves no trace for the next file.
  • Math.random at 0.5 serves two purposes: the delay is always 900 ms and failSometimes never fails. But crypto.randomUUID() does not use Math.random, so the id is still unique and in UUID format.
  • complete is a small local helper so as not to repeat runAllTimersAsync for every request that should finish successfully.
  • The 409 test checks the error's data, which translateError needs in order to compose "The Polen Room is already booked on...". If someone changed them, the translated message would come out with empty slots.

Solution 3.

// In LoginView.spec.js, inside the describe
it('shows "Signing in…" and disables the button while authenticating', async () => {
  const { promise, resolve } = Promise.withResolvers()
  vi.mocked(api.session.authenticate).mockReturnValue(promise)
  const { wrapper, router } = await mountLogin('/login')

  await wrapper.get('input[type="email"]').setValue('[email protected]')
  await wrapper.get('input[type="password"]').setValue('colmena')
  await wrapper.get('form').trigger('submit')

  const submitButton = wrapper.get('button[type="submit"]')
  expect(submitButton.text()).toBe('Signing in…')
  expect(submitButton.element.disabled).toBe(true)

  resolve({ ...LAURA })
  await flushPromises()

  expect(router.currentRoute.value.name).toBe('dashboard')
  wrapper.unmount()
})

We do not use the signInWith helper, because it does a flushPromises at the end and we need to look between the submission and the response. The controlled promise keeps the authentication "in flight" for as long as we like; the await on trigger('submit') is enough for Vue to render the submitting state.

Conclusion

The dependencies a test does not control (the API, time, chance, the browser's dialogs, the router) make it slow and unpredictable, and the solution is to replace them with test doubles: dummies, stubs, spies, mocks and fakes, depending on whether you need to control what they return, check how they are used or both. Vitest creates them with vi.fn (with mockResolvedValue, mockRejectedValue, mockImplementation and their Once variants, and assertions such as toHaveBeenCalledWith), vi.spyOn for existing methods such as console.log, Math.random or window.confirm, and vi.mock for entire modules, which in Colmena comes down to mocking the @/api facade. Mocks are cleaned up with vi.resetAllMocks() and vi.restoreAllMocks(); promises are awaited with flushPromises and controlled with Promise.withResolvers; the clock is governed with vi.useFakeTimers, vi.setSystemTime and advanceTimersByTime(Async); expensive children are replaced with global.stubs, and the router is preferably provided real and in memory with createTestRouter from tests/router.js, which mountWithPlugins now accepts through its router option. MSW remains the tool for the day Colmena talks HTTP to a real server. With all this, RoomDetailView, LoginView, ReceptionClock and the simulated API have deterministic tests that run in seconds.

In RoomDetailView and LoginView we have used the real Pinia stores, but only in passing, as part of the journey. And yet a good deal of Colmena's most delicate logic lives precisely in them: the catalogue cache, booking overlaps, optimistic cancellation with its rollback, which bookings a member sees and which a manager sees, session persistence. In the next lesson we will test them thoroughly and in their own right, and we will learn to mount components with stores prepared to measure and to test composables, in Testing Composables and Stores.

New edition · October 2026

Vue.js Course

Module 1: Introduction to Vue.js

Module 2: Vue.js Basics

Module 3: Vue.js Components

Module 4: Vue Router

Module 5: State Management with Vuex and Pinia

Module 6: Vue.js Directives

Module 7: Vue.js Plugins

Module 8: Testing in Vue.js

Module 9: Advanced Vue.js Concepts

Module 10: Building and Deploying Vue.js Applications

Module 11: Real-World Vue.js Projects

© Copyright 2026. All rights reserved