Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

testing svelte component's onMount #243

Answered by mcous
csandeep asked this question in Q&A
Discussion options

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();
});
You must be logged in to vote

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

Comment options

The issue #222 contains information about that absence of onMount.

You must be logged in to vote
0 replies
Comment options

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

You must be logged in to vote
0 replies
Answer selected by yanick
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
🙏
Q&A
Labels
None yet
3 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.