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

我写了一个 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)。


应用程序测试.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"); // ❌

});

有一条错误信息:


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检查此行为。


有人知道为什么这个测试失败了吗?


ITMISS
浏览 108回答 2
2回答

慕娘9325324

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

胡子哥哥

如果您在文件开头导入:import&nbsp;{&nbsp;screen&nbsp;}&nbsp;from&nbsp;'@testing-library/dom'最后你把这个:&nbsp;expect( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;await&nbsp;screen.findByText('test'), &nbsp;&nbsp;&nbsp;&nbsp;).toBeVisible()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript