Description
I'm in the process of writing some testing examples and documentation for the Svelte community and was hoping to use the testing-library
DOM helpers to do so, they have quickly become the gold standard for DOM testing in a node environment and I'd love to recommend them. However, I've come across a problem with the way the render
method currently works.
Currently render
expects the component constructor to appear as the default export on the compiled output but this is only true when compiling to esm
or using a bundler. When compiling to cjs
via svelte.compile
the component constructor is actually on the default
property of the compiled output object. This is because cjs
doesn't allow named and default exports like esm
does, so Svelte has adopted an, admittedly strange, alternative. Here is an example of the output when compiling to cjs
.
The reason this hasn't been a problem in your internal tests is because you are using a Jest transform that uses rollup to bundle inside the transform (this might be problematic too for many users, but I'll make another issue to discuss that).
The result of this is that transforms or compilation methods that use the svelte API rather than using a bundler will be confusing to users since they would need to do something like:
import App from './App.svelte';
const { getByText } = render(App.default);
I think it would be worth ensuring the users expectations are met here since the fix is very simple. We just need to check to see if the default property exists on the Component
object before using Component
directly. I have been using a modified render
function that solves this like so:
const ComponentConstructor = Component.default || Component;
const component = new ComponentConstructor({
...options,
target,
});
If you're interested in this change, I would be happy to PR it.
Thanks again for creating this Svelte version of testing-library, the documentation and community are great and it gives Svelte users a great option for testing their components which we have been lacking for some time.