Using hand-rolled component stubs
In this section, we’ll look at a simple but effective way of mocking components, by building hand-rolled component stubs. This isn’t as clever as using a component mock library, but it’s simpler and easier to understand. Often, the simplest approach is the best choice.
To recap what we’re trying to do: we have a child component that we want to avoid rendering, perhaps because it has mount behavior or it’s a complex third-party component.
Hand-rolled component stubs rely on Vitest’s vi.mock
function combined with a special __mocks__
directory. You create a stub component with the same name as your component, but inside a __mocks__
directory at the same level as the component itself. Then, you instruct Vitest to use the mock using the vi.mock
statement placed at the top of your test file. This will mean the entire test suite uses the mock.
We can demonstrate this using the page route component test suite...