I recently complained about Svelte testing and highlighted things I’d change.
One issue I ran into was it appeared Svelte Testing Library did not remove component instances from the virtual DOM between tests.
Well, after publishing my post, I spent some time digging into the code and it turns out there is a function, cleanup(), and it only runs after each test with globals: true
in your vite.config.ts
. Basically, Svelte Testing Library checks if there’s a globally available afterEach()
function and calls cleanup()
if there is.
If you read the setup docs, the example code has globals: true
set, but it was easy to miss. So, I submitted a pull request updating the Testing Library docs to call out this necessary step. As of two weeks ago, it’s been merged!
The React, Preact and Vue libraries also require a globally available afterEach()
to run cleanup()
, so I updated their docs as well. Hopefully this will help people avoid this bug in the future.
So yeah, apologies to the good folks working on the Svelte Testing Library. It absolutely does clear the virtual DOM between tests - you just have to use it correctly 😄.