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:
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.
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 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
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!
I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.