A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://stackoverflow.com/questions/63343948/how-to-test-svelte-input-reactivity below:

javascript - How to test svelte input reactivity?

I wrote a svelte component App in which you can write a sentence in an input and the sentence will be render in a h1.

App.svelte

<script>
  let sentence = "Hello world";
</script>

<main>
  <h1>{sentence}</h1>
  <input
    value={sentence}
    type="text"
    on:input={(value) => {
      sentence = value.target.value
    }}
  />

</main>

But when I tried to test this behaviour using @testing-library/svelte, the input is not reactive and the text in h1 is still "Hello world" (but the value in the input has changed according to the first expect).

App.test.js

import { render, fireEvent } from "@testing-library/svelte";
import App from "./App.svelte";

it("should write in input", async () => {
  const { container } = render(App);
  const input = container.querySelector("input[type=text]");

  await fireEvent.change(input, { target: { value: "test" } });

  expect(input.value).toBe("test"); // ✅
  expect(container.querySelector("h1").textContent).toBe("test"); // ❌
});

Jest error message:

Expected: "test"
Received: "Hello world"

   8 |   await fireEvent.change(input, { target: { value: "test" } });
  10 |   expect(input.value).toBe("test");
> 11 |   expect(container.querySelector("h1").textContent).toBe("test");
  12 | });

You can check this behaviour using the codesandbox.

Has someone an idea why this test is failing?


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4