How to test Svelte components
I've been looking into Svelte, and while most of the info that I'm looking for can be found in the documentation, there's one piece missing. There's no section on how to test components, so I went to explore this area.
The first place where I was looking, was the Svelte repository itself. It contains tests that seem simple at first, like this one. The only problem that I have, is that it requires me to orchestrate the test setup.
After taking a look at the Svelte repository, I quickly came across the Svelte Testing Library. I'm the creator of the Angular Testing Library, and because of the Testing Library has a similar API across all frameworks, I was quickly used to it.
Writing tests with the Svelte Testing Library can be done with all test, in this article I'm using Jest.
The first step is to install the dependencies:
After the installation is complete, Jest and Babel have to be configured.
To configure Jest, create a
jest.config.js file in the root of the project.
For Babel, create a
babel.config.js file in the root of the project.
The last step of the setup is to add a script inside the
To use the Svelte Testing Library, the
@testing-library/svelte package has to be installed.
After all the setup, we can start writing tests.
The test will look familiar to you if you've already used a Testing Library.
- to create the component, use the
- to interact with the component, use the
query(All)Bymethods, and the methods on
- as a bonus, use the jest-dom matchers
To pass props to a component, make use of the Component Options
Everything is set, and now we can finally run the tests. Run the following command:
Please consider supporting me if have you enjoyed this post and found it useful: