如何测试苗条的输入反应性?

How to test svelte input reactivity?

我写了一个精巧的组件 App,您可以在其中写一个 input 的句子,然后该句子将在 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>

但是当我尝试使用 @testing-library/svelte 测试此行为时,输入没有响应并且 h1 中的文本仍然是 "Hello world"(但输入中的值已更改根据第一个 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 错误信息:

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 | });

您可以使用 codesandbox 检查此行为。

有人知道此测试失败的原因吗?

TL;DR:

按照您在评论中的建议使用fireEvent.input(...)

原意:

我想知道这是否与当 Svelte 订阅 input 事件时触发 change 事件有关。尝试将其更改为 on:change,您将看到测试通过。现在,理想的情况是 fireEvent 触发 'input' 事件。

如果在文件开头导入:

import { screen } from '@testing-library/dom'

最后你把这个:

 expect(
      await screen.findByText('test'),
    ).toBeVisible()