我写了一个 svelte 组件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)。应用程序测试.jsimport { 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"); // ❌});有一条错误信息: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检查此行为。有人知道为什么这个测试失败了吗?
2 回答

慕娘9325324
TA贡献1783条经验 获得超4个赞
长话短说:
fireEvent.input(...)
按照您在评论中的建议使用。
原意:
我想知道这是否与它change
在 Svelte 订阅事件时触发事件有关input
。尝试将其更改为on:change
,您将看到测试通过。现在,理想的情况是fireEvent
触发一个'input'
事件。

胡子哥哥
TA贡献1825条经验 获得超6个赞
如果您在文件开头导入:
import { screen } from '@testing-library/dom'
最后你把这个:
expect( await screen.findByText('test'), ).toBeVisible()
添加回答
举报
0/150
提交
取消