-
Notifications
You must be signed in to change notification settings - Fork 33
-
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();
});
Beta Was this translation helpful? Give feedback.
All reactions
We traced this to an issue with how Vitest likes to configure its resolution rules: unlike Jest, Vitest will prefer server module bundles - rather than browser bundles - unless specifically configured otherwise. In the server bundle of Svelte, onMount
is a no-op.
In the latest setup docs we have included a simple way to configure Vitest to use browser bundles. There's more than one way to configure this, with different tradeoffs. See the thread in #222 for more information
Replies: 2 comments
-
The issue #222 contains information about that absence of onMount
.
Beta Was this translation helpful? Give feedback.
All reactions
-
We traced this to an issue with how Vitest likes to configure its resolution rules: unlike Jest, Vitest will prefer server module bundles - rather than browser bundles - unless specifically configured otherwise. In the server bundle of Svelte, onMount
is a no-op.
In the latest setup docs we have included a simple way to configure Vitest to use browser bundles. There's more than one way to configure this, with different tradeoffs. See the thread in #222 for more information
Beta Was this translation helpful? Give feedback.