Using a component mock library
In the last chapter, you saw how you can use vi.fn
to spy on functions. The svelte-component-double
npm package can be used in a similar fashion, achieving the same effect as the hand-rolled mocks you’ve just learned about.
The package includes matchers such as toBeRendered
and toBeRenderedWithProps
to check that the component is indeed rendered in the way you wanted.
Let’s split this into a couple of parts: installing the library and writing tests.
Installing the library
The library requires a bit of setup to get the relevant matchers into place:
- Run the following command to install the package:
npm install --save-dev svelte-component-double
- Then, create a new file named
src/vitest/registerSvelteComponentDouble.js
with the following content. It registers the matchers and also gives us global access to thecomponentDouble
function, which is not required but makes mock setup easier:import { expect } from 'vitest...