Unit Testing
Unit tests tell you within seconds whether the logic behind your pages still works, before a browser is involved. The Storefront Application V3 runs them with Vitest, and this page shows how to write and run them for each part of the code: a mapper (code that turns Storefront API data into the shape a page uses), a service, a composable (a reusable Vue function that holds state or behavior) or a component.
The projects
The Vitest suite is split into parallel projects. Each one covers a layer of the codebase and runs in the test environment that layer needs: a DOM for components, plain Node for everything else. The DOM comes from happy-dom, a lightweight browser DOM that runs inside Node.
The project names in vitest.config.ts start with v3:boilerplate::
v3:boilerplate:components(src/client/**/*.vue.test.ts): Vue components, inhappy-dom, somount()has a real DOM to render into.v3:boilerplate:client(src/client/**/*.test.ts, excluding.vue.test.ts): client-side composables and utilities, in Node, since most composable logic doesn't need a DOM at all.v3:boilerplate:shared(src/shared/**/*.test.ts): types and utilities used by both client and server, in Node.v3:boilerplate:server(src/server/**/*.test.ts): controllers, services, and mappers, in Node.v3:boilerplate:i18n(src/i18n/**/*.test.ts): locale files and message loading, in Node.v3:boilerplate:scripts(the test files inscripts/, excludingcache.test.ts): the application's Node scripts, in Node.cache.test.tsneeds a live server and has its own Vitest config, so the default run skips it.
Every project except scripts shares the same path aliases (@client, @server,
@shared, @assets, @test, and the @cms-* aliases), so an
import in a test file looks the same regardless of which of them runs it.
Running tests
pnpm test:ci can fail even when every test passes. vitest.config.ts sets minimum coverage thresholds for lines, statements, branches and functions, and the command fails when the coverage falls below one of them.
Server-side testing
Server tests combine mocked services, a mocked session, and a mocked context of Hono, the web framework that runs the server. They then exercise a controller, an oRPC procedure (a typed server function that the client calls to change data), or a service directly. The test double factories live in two places to keep them separate and focused.
createMockRequestContext, createMockSession, and createMockStorefrontContext come from
@scayle/storefront/test, re-exported through src/test/utils/context.ts so server test files
have one import path. These live in the SDK because they're generic test doubles every SCAYLE
storefront needs, not specific to this application.
createMockMapperRegistry in src/test/utils/context.ts wraps the helper of the same name from @scayle/storefront/test. It fills the registry's i18n slot with a real ServerI18nService rather than a stub, so a test using it sees actual translated strings instead of asserting against a mock. The SDK can't do this itself because ServerI18nService is application code the SDK must not depend on.
An oRPC route test calls the procedure directly with call() from @orpc/server, and asserts on
either the resolved value or the typed error the procedure throws:
A controller test builds the same shape of mocked context and connects the real services and mappers the controller depends on, so the test exercises real mapping logic against a mocked API layer rather than mocking the mapping itself.
Client-side testing
Client-side code splits the same way the project config does: a composable with no DOM dependency
is tested in Node with the composable's own dependencies mocked, and a Vue component is tested in
happy-dom with mount().
A pure-logic composable can be tested directly. usePageMeta keeps the page title in module-level state that every caller shares, so each test resets the module with vi.resetModules() to start from an empty title. The composable ignores writes during a server render, so the test sets SSR to false first:
currentTitle is read-only, so the test changes the title through setCurrentTitle().
A composable that depends on Vue's injection needs its dependencies mocked before the composable itself is imported, using vi.hoisted() so the mock values exist before vi.mock() runs. Replace only what the test needs. vi.mock('vue') with a bare factory would remove every other Vue export, such as ref, which useAnnouncer imports. Spread the real module with vi.importActual() and override only inject:
A composable that reads the page data of Inertia, which hands the server's page data to the Vue pages, uses @test/utils/inertia's
createReactivePage(). It returns a reactive() mock, so a test can change component or
props mid-test and see the composable react, rather than remounting for every scenario:
ReactivePageMock is a type from @test/utils/inertia. Without the type, the later assignment mocks.reactivePage!.component = 'Checkout' does not typecheck.
@test/utils/inertia also exports createDeferredStub(). It stubs Inertia's <Deferred> component behind a
mutable state.useFallback flag, so a test can assert on both the loading skeleton and the loaded
content without remounting between the two. Import it from @test/utils/inertia. A second createDeferredStub(label) in @test/utils/deferredStub does something else: it builds a routed component that stays pending, to prove that a parent wraps it in Suspense.
A composable that only works inside a component's setup context, useOverlay is the real
example, gets tested by mounting a small component that calls the composable and exposes its
return value, rather than trying to call the composable as a plain function. useOverlay().create(loader, { props, preload }) takes a function that loads the overlay component and returns triggerAttrs for the opening element, plus open(), close() and toggle(). The test helper mountOverlay calls it inside a Trigger component and mounts that next to SFOverlayHost, which renders the overlay:
A test that only needs to read what a component passes to its overlays can use createOverlayTestPlugin() from @test/utils/overlay instead.
Component tests mount the real component with Vue Test Utils and mock vue-i18n the same way
composable tests do. mount() renders the whole component tree, children included, so the test sees what a customer sees. shallowMount() replaces the child components with empty stubs. Use it when the children are heavy or have their own tests and you only check how the component passes props and events to them, as SFProductGrid.vue.test.ts does.
The directive v-dialog is not a component, so its test mounts a small component that uses it. happy-dom implements HTMLDialogElement.prototype.show(), showModal() and close(), so the test spies on them to observe the calls. Use vi.spyOn() with mockImplementation(). Because the config sets restoreMocks, every test gets happy-dom's own methods back:
Best practices
Structure tests as arrange, act, assert
Set up mocks and data, call the code under test, then assert, and keep the three visually separate.
Name tests by behavior, not mechanism
it('rejects an unauthenticated request') names what broke. it('works') does not.
Mock only what the test needs to isolate
Over-mocking hides real integration problems behind a green test. If a dependency's actual behavior matters, keep it real.
Reset mock state between tests
Vitest resets most of this for you. The config sets restoreMocks, unstubEnvs and unstubGlobals in every project, so spies from vi.spyOn(), vi.stubEnv() values and vi.stubGlobal() values are undone before each test. Vitest also clears the call history of every mock before each test, and the components project unmounts every mounted wrapper after each test. A hook that only calls vi.clearAllMocks() or vi.restoreAllMocks() does nothing, so leave it out.
Some state needs a manual reset:
- Module-level state, such as the title in
usePageMeta. Callvi.resetModules()inbeforeEachand import the module inside the test, as in the sample above. - A mutable object that you share between tests, such as
injectStateinuseToast.test.tsorreactivePage.componentinusePageComponent.test.ts. Set it back to its starting value inbeforeEach. - A mock you assign directly, such as
HTMLDialogElement.prototype.show = mockShow. Vitest restores spies, not assignments, so the stub would stay for the rest of the file. Usevi.spyOn()instead.
Run one test over several inputs
it.for() runs the same assertion across several rows without duplicating the test body. This helps with boundary conditions such as an empty array, a missing optional field, or a value at a limit. The application's testing guidelines (docs/testing-guidelines.md in the application) set the threshold: three or more tests that differ only in input and expected output become one table. Below that, separate tests read more clearly. Cover the edge cases in the table, not only the happy path. Vitest passes each row to the test as one argument, so destructure an array row in the parameter list: it.for([[1, '1st'], [7, '7th']])('formats day %i as %s', ([day, expected]) => { ... }).
Troubleshooting
A test that mocks a module still calls the real implementation
Issue: vi.mock() is in the test file, but the code under test still appears to run the real
function instead of the mock.
Possible causes: The module under test was imported (even indirectly through another module)
before vi.mock() had a chance to hoist, most often because the mock value was computed inline
instead of through vi.hoisted().
Solution: Move any value the mock factory references into vi.hoisted(() => (...)) so it's
guaranteed to exist before Vitest hoists the vi.mock() call above the imports.
Prevention: Default to vi.hoisted() for any mock value that isn't a bare literal, rather than
discovering the hoisting order problem after a test silently exercises the real dependency.
A component test fails with a missing browser API
Issue: A component test throws an error about a missing global (a DOM method, a browser API) that exists in a real browser but not in the test environment.
Possible causes: The test file is running in the client or server Vitest project (Node
environment, no DOM) rather than the components project (happy-dom), usually because the file
doesn't end in .vue.test.ts and so doesn't match the components project's include pattern.
Solution: Confirm that the file name ends in .vue.test.ts if it mounts a Vue component. If the
missing API is one that happy-dom does not implement, or implements without the behavior your test needs, stub it with vi.stubGlobal(). For example, happy-dom never fires ResizeObserver callbacks, so SFToastContainer.vue.test.ts stubs ResizeObserver with a class that records its callbacks and fires them from the test. vi.stubGlobal() is undone before the next test. To observe calls to a method that happy-dom does implement, such as HTMLDialogElement.prototype.show, use vi.spyOn().
Prevention: Keep component tests in .vue.test.ts files and pure-logic tests in plain
.test.ts files, so each lands in the project whose environment it actually needs.