vitest and svelte component's onMount
Asked Answered
A

1

5

I'm trying to use Svelte to create a simple reactive component. The component loads data from an api server onMount and updates a reactive value (which updates a html element).

I have a simple vitest that renders the component and verifies the value of the html element. However while running under vitest the onMount is never called and hence the api call is never made. What am I missing ?

Component.svelte:

<script>
    import { onMount } from 'svelte';

    export let name = 'world';

    onMount(async () => {
        console.log('chat onMount event!');
        const response = await fetch('http://localhost:8081/api');
        // for this example, assume name returned by api is FOO
        name = data.name;
    });

</script>

<div id="#element">
    <b> Hello {name}</b>
</div>

index.test.js:

import { expect, test } from 'vitest';
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/svelte';
import Component from '../src/lib/Component.svelte';

test('should render', () => {
    render(Component);

    const heading = screen.getByText('Hello FOO');
    expect(heading).toBeInTheDocument();
});
Arlettearley answered 29/6, 2023 at 2:7 Comment(0)
A
6

After some sleuthing I stumbled on this issue: https://github.com/vitest-dev/vitest/issues/2834

As I'm running Svelte 4.0.0 the onMount is no longer invoked under vitest, hence I had to ad this to vite.config.js to make it work:

{
      test: {
        alias: [{ find: /^svelte$/, replacement: 'svelte/internal' }],
        ....
       },
       ....
}
Arlettearley answered 4/7, 2023 at 20:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.