playwright icon indicating copy to clipboard operation
playwright copied to clipboard

[Bug]: Unexpected behaviour of svelte's onMount when running component tests

Open evanna90 opened this issue 9 months ago • 2 comments

Version

1.51.1

Steps to reproduce

  1. Setup basic svelte project with experimental-ct-svelte, vite and typescript Svelte: 4.2.18 @playwright/experimental-ct-svelte: 1.51.1 vite: 5.4.15 typescript: 5.7.2

  2. Add the following component:

// MyComponent.svelte
<script lang="ts">
  import { onMount } from "svelte";

  let initVal = 'initial';

  onMount(() => {
    initVal = 'mounted';
    console.log('initial value' + initVal);
  })
</script>

<div>{initVal} </div>
  1. Add test
test('test', async ({mount}) => {
    const component = await mount(MyComponent, {});
    await expect(component).toContainText('mounted');
})

Expected behavior

Test passes. I should be able to see initial value mounted inside the console (while running npm run test-ct debug or inside the trace)

Actual behavior

Test fails, as initVal is still set to 'initial' The console is empty.

Additional context

For some reason it looks like onMount is not even called in MyComponent. If it did, we should have at least seen the console.log.

To rule out the possibility that svelte update occurrs after playwright's expect is called, I tried two other solutions instead of using onMount on MyComponent:

//Solution 1

function setVal() { 
    initVal = 'mounted';
    console.log('initial value' + initVal);
  }

<div use:setVal>{initVal} </div>
// Solution 2

  $: {
    if (initVal === 'initial') { initVal = 'mounted'; console.log('initial value' + initVal); };
  }

Both of them seem to work fine - the test passes and console.log is displayed properly. The test fails only when onMount is used, which seems like a very unexpected behavior.

Environment

System:
    OS: Windows 11 10.0.26100
    CPU: (8) x64 Intel(R) Core(TM) i5-1035G1 CPU @ 1.00GHz
    Memory: 2.78 GB / 11.77 GB
  Binaries:
    Node: 22.11.0
    npm: 10.9.0
  IDEs:
    VSCode: 1.86.1
  npmPackages:
    @playwright/experimental-ct-svelte: ^1.51.1 => 1.51.1

evanna90 avatar Mar 27 '25 14:03 evanna90

This is rather unusual indeed. Digging into this a bit reveals that Vite is bundling Svelte's SSR implementation, which has stubs for onMount, beforeUpdate, and afterUpdate (https://github.com/sveltejs/svelte/blob/svelte-4/packages/svelte/src/runtime/ssr.js). I poked around with trying to force it to not enable SSR, but I was unsuccessful.

This appears to have been working in the past, so something likely changed with either Vite or Svelte to break it.

agg23 avatar Mar 27 '25 17:03 agg23

I experienced the same bug, but on my side my tests only failed, if I run my complete test suite in parallel. If I run only one test at once, onMount is successfully initialized and called. However, with multiple tests running in parallel, onMount is not called

JE4GLE avatar Jun 17 '25 19:06 JE4GLE