Search code examples
testingsveltesveltekitvitest

Confusion about Unittesting with Vitest, while only having +page.svelte files


For my university work I need to learn Testing using Vitest in a Svelte Project. So far I understand the basics and was able to write basic tests. Now I need to test the code written by my colleagues in Svelte. The Problem is that I don't really know what exactly to import, if all I have are +page.svelte files. What do I need to import to test a specific function?

For example using:

import footer from "../src/routes/+layout.svelte";

describe("Layout Test", () => {
    test("that footer is being rendered", () => {
        const host = document.createElement('div');

        document.body.appendChild(host);

        const instance = new footer({target: host});

        expect(instance).toBeTruthy();
    });

I get a passed test. Did this actually test if the footer exists or am I misunderstanding something? Did it even test the footer from the +layout.svelte page?

Any help is greatly appreciated <3

Tried researching the problem, expected it to solve my question, but no source i found helped.


Solution

  • If you want to test components, you can use Svelte Testing Library in combination with vitest.

    You can find examples in the "Example" section but basically, you should render components using the "render" function and you get specific elements by test-id or text, etc... (Check the coreApi -> queries).

    In your case, I would do:

    import { render } from '@testing-library/svelte';
    import { describe, it, expect } from 'vitest';
    import footer from "../src/routes/+layout.svelte";
    
    describe("Layout Test", () => {
        it("renders the footer", () => {
            const { getByTestId } = render(footer);
            expect(getByTestId('footer')).toBeTruthy();
        });
    });
    

    Note: remember to add a "data-testid" to your footer if you wish to use the "getByTestId" query.