Tim Deschryver

How to test Svelte components

Published | Modified

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.

Jest Setup

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:

The Babel compiler has to be installed to use the ES6 syntax while writing tests. To compile Svelte components, it's also needed to install svelte-jester.

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 package.json file:

Svelte Testing Library Setup

To use the Svelte Testing Library, the @testing-library/svelte package has to be installed.

Writing a test

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 pass props to a component, make use of the Component Options

Running tests

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:

Buy Me A Coffee PayPal logo
Support the blog Share on Twitter Discuss on Twitter Edit on GitHub