A couple of months ago, I switched from using React to using Svelte for my side projects. Since I'm a TDDist at heart, I naturally wanted to figure out how to write good unit tests for this new component framework. Turns out not many people are doing that yet so, yep, I went down that rabbit hole. I spent a great deal of time figuring out how to write effective unit tests with Svelte.
I’ve learned enough now so it’s time to share what I learned with you.
But first... here's a question that I hear a lot.
It’s a fairly popular opinion in the front-end community that unit testing is a waste of time, and counter-productive. If people write tests at all, they will be system tests that operate at a high level.
Writing unit tests for components is not straightforward, and for novices it is all too easy to get stuck. Techniques like mocking are hard—really hard-—to get right. On top of that, components are so much about declarative code that it can often seem that unit tests are simply parroting what’s written in the production code.
To the first point, unit testing takes practice to get right. I hope this series puts you on solid footing.
To the second point, I’d agree. Don’t test “static” data. But components are very, very rarely just static data (I’ll come back to this point in the next part of this series.)
The benefits of unit testing on the front-end are the same as on the back-end: assisting you with better design; quickly pinpointing errors; helping you write high-quality code at lightning speed. If you're following TDD [this series is not about TDD] then unit tests also give you a great structure for pairing and mobbing on your work.
The “let’s do things more simply” argument really chimes with me. React is too complicated for my liking, and most React codebases I’ve seen are scrappy without any real structure.
I also buy in to the “lean web” idea, that we should do our bit to save the planet by not deploying large-size libraries like React around by avoiding unnecessary computations when possible. Svelte is a great step in that direction.
Plus, I was ready to try something new.
Now let’s talk about testing...
Because of the whole idea of embracing simplicity and removing bloat, I also decided to step away from Jest and move back to Jasmine. I’ve also tried out the techniques in this series with Mocha, and in this series I’ll provide instructions for both Jasmine and Mocha.
Just like Vim and Emacs, Jasmine is ancient and it works as well as I need it to 😆
You do not need to know Svelte to use this guide, but if you don’t I suggest you try at least the first few sections of the Svelte tutorial first—it’s great!
It’ll also help if you’ve got basic awareness of the standard test functions:
You can look at my GitHub repo dirv/svelte-testing-demo for an example of how to put all this together.
That’s it for the introduction. In Part 2, we’ll look at how to set up up a Svelte unit testing environment.