How to test Svelte components

Tim Deschryver

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 link

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 link

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

Writing a test link

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 link

Everything is set, and now we can finally run the tests. Run the following command:

Feel free to update this blog post on GitHub, thanks in advance!

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at PayPal logo

Share this post on

Twitter LinkedIn