我写了一个精巧的组件 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 检查此行为.
有人知道为什么这个测试失败了吗?
最佳答案
长话短说:
按照您在评论中的建议使用 fireEvent.input(...)
。
最初的想法:
我想知道这是否与当 Svelte 订阅 input
事件时触发 change
事件有关。尝试将其更改为 on:change
,您将看到测试通过。现在,理想的情况是让 fireEvent
触发 'input'
事件。
关于javascript - 如何测试 slim 的输入 react 性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63343948/