Using Component Mocks to Clarify Tests
The preceding chapter introduced the concept of a test double and showed how vi.fn
can be used to swap out unwanted behavior within your Vitest test suites. The same technique can be used for Svelte components, but it’s a little more complicated.
Imagine you’re writing unit tests for a component named Parent
, and that component itself renders another developer-defined component, named Child
. By default, when your tests render Parent
, Child
is rendered too. But using a component mock can stop that from happening. It swaps out the real Child
for a test double.
There are various reasons why you’d want to do this:
- The
Child
component already has its own unit test suite, and you don’t want to repeat yourself (a form of overtesting, described in detail in the Avoiding component mocks section) - The
Child
component has behavior on mount, such as fetching data via the Fetch API, that you’d rather avoid...