Yesterday I discovered that it’s actually possible to do unit testing with Svelte! When I last tried to find how to unit test with Svelte at the end of 2019 it seemed that was something that wasn’t yet possible. Svelte still says there’s no good answer to this yet so I’d taken their word for it. But it’s very possible!
This together with the recently released TypeScript support really feels like a game changer for using Svelte in bigger projects and pushing it as an alternative when working with clients and colleagues.
So how do you do it?
- First thing, follow the setup instructions on Testing Library.
According to the setup page that should be enough. For me, that was not the case. All import
statements in .js
files broke when I ran the tests. Svelte takes care of .svelte
files, so those imports work. But if you’ve written Svelte apps before, you might know that sometimes you include regular .js
files for utils or services, and they might use import
statements too. The case for me was my stores.js
that had import { writable } from 'svelte/stores'
, as well as all of my test files.
The test files are all .js
files, unless you work with TypeScript, so imports will be broken there too.
Some error messages you might come across:
Test suite failed to run
import ‘@testing-library/jest-dom/extend-expect’;
SyntaxError: Unexpected string
or
Jest encountered an unexpected token
import { render, fireEvent } from ‘@testing-library/svelte’;
SyntaxError: Unexpected token {
You could of course get around this by using require()
instead of import
throughout your app. The Testing Library says Babel and TypeScript are optional, but I’m not sure I agree. I don’t know of anyone who uses require
statements for imports in a frontend application. This leads us to…
3. That’s it. Your tests should run.
I didn’t really find anyone else with this problem because everyone seemed to be using Babel or Typescript from the start.
Tips for testing Svelte components
Here are some tips on how to test events, and how to render the components in the test files.
Here are some more good to knows for using jest-svelte.
Let me know if this helped you out, if it’s not working for you, or if something’s missing!
Thanks for reading ❤
– Bill Kurtson, Senior Frontend-developer