I'm struggling to understand how to effectively test SvelteKit components like this one.
I want to test the selectedTaxon
property, and one approach is to mock the TaxonLinkButton
component. However, I'd like to find a more elegant solution. Is there a way to test which props are passed to the TaxonLinkButton
component? Or is there a way to directly check the reactive property selectedTaxon
of the component?
What's the best approach? Please feel free to guide me if my testing approach isn't logically correct.
<script lang="ts">
import { page } from '$app/stores';
import TaxonLinkButton from '../TaxonLinkButton.svelte';
import type { Taxon } from '$types/product.type';
export let taxonomies: Taxon[];
let selectedTaxon: Taxon | null = null;
$: {
const permalink = $page.url.pathname.replace(/\/t\//g, '');
taxonomies.find((taxonomy) => {
if (taxonomy.permalink === permalink) {
selectedTaxon = taxonomy;
return true;
}
});
}
</script>
<div data-testid="test-taxonomy-three-component" class="flex flex-col mt-5 lg:mt-0">
<TaxonLinkButton {selectedTaxon} >
{taxonomy.name}
</TaxonLinkButton>
</div>
When you test, you can compile the component in dev mode. That way each component will expose an extra
component.$$.hmr_cmp
object, which has a$capture_state()
getter function that returns the entire local state of the component.I put together a stackblitz demo, open console to see log. You can test against
component.$$.hmr_cmp.$capture_state().selectedTaxon
directly.