12

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 ...

Get Svelte with Test-Driven Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.