Search code examples
sveltekitvitest

How do I test a route slug component in sveltekit?


I have this page:

src/item/[slug]/+page.svelte

trying to render it in vitest gives me an error:

  ...
  render(item)
  ..

After a trial and error session I narrowed down the cause, it is because the component is a slug, the parameter doesn't get initialized in the tests.

import {page} from '$app/stores'

let param = $page.params;
let slug = param.slug

how can I initialize it in my test file?


Solution

  • Ok,for a work around I placed the entire contents of my +page.svelte to a new svelte component file and created an export variable for the slug value

    item.svelte

    <script>
    export let itemId;
    </script>
    <div>
    ...
    
    

    and in my slug page this is the only code remained: +page.svelte

    <script>
    import {page} from '$app/stores'
    
    let param = $page.params;
    let slug = param.slug
    </script>
    
    <item bind:slug={slug}></item>
    

    and just ran my tests on the separate component.