Skip to content

[Svelte 5] Functions using onMount fail tests due no component initialization #13136

@karbica

Description

@karbica

Describe the bug

Functions (not components) that call onMount throws an error. The error states that onMount can only be used in component initialization.

'lifecycle_outside_component
`onMount(...)` can only be used during component initialisation'

The purpose of calling onMount in a function is so that mounting logic can be done on behalf of the component. The attached StackBlitz project showcases an example.

Reproduction

Linked below is a working sample. In summary, there is a useMouseCoords function that attaches mousemove listeners in an onMount function that updates state runes. That function is then used inside App.svelte to read those state runes after calling the onMount function.

https://stackblitz.com/edit/vitejs-vite-2fltxz?file=tests%2Fone.test.ts

Function sample

// use-mouse-coords.svelte.ts

import { onMount } from 'svelte';

export function useMouseCoords() {
  let x = $state(0);
  let y = $state(0);

  function onMousemove(e: MouseEvent) {
    x = e.clientX;
    y = e.clientY;
  }

  console.log('useMouseCoords: outside of onMount');
  function init() {
    console.log('useMouseCoords: inside of onMount');
    window.addEventListener('mousemove', onMousemove);
    return () => window.removeEventListener('mousemove', onMousemove);
  }

  onMount(init);

  return {
    get x() {
      return x;
    },
    get y() {
      return y;
    },
  };
}

Test sample

// one.test.ts

import { it, expect } from 'vitest';
import Counter from '../src/lib/Counter.svelte';
import { useMouseCoords } from '../src/lib/use-mouse-coords.svelte.ts';
import { render, screen } from '@testing-library/svelte';

it('runs correctly when rendering a component', () => {
  render(Counter); // this includes an `onMount` call
  expect(screen.getByRole('button')).toBeInTheDocument(); // PASS
});

it('throws an error about onMount can only be used in component initialization', () => {
  expect(() => useMouseCoords()).toThrowError(
    'lifecycle_outside_component\n`onMount(...)` can only be used during component initialisation'
  ); // PASS
});

Logs

N/A

System Info

System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 18.20.3 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 10.2.3 - /usr/local/bin/npm
    pnpm: 8.15.6 - /usr/local/bin/pnpm
  npmPackages:
    svelte: ^5.0.0-next.243 => 5.0.0-next.243

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions