【问题标题】:userEvent.type inputs only last character when wrapped in actuserEvent.type 仅在包含在 act 中时输入最后一个字符
【发布时间】:2021-01-05 19:26:20
【问题描述】:

我在用户事件 github 中发现了一个问题,它说它已在 12.0.1 版本中解决,但我使用的是 12.1.5 版本,并且一直收到错误消息。

import React, { Fragment } from "react";
import { render, act } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import App from "./App";

test("Gets a code and renders it in a new route", () => {
  const { getByLabelText } = render(<App />);
  act(() => {
    userEvent.type(getByLabelText("Code:"), "12345");
  });
  expect(getByLabelText("Code:")).toHaveValue("12345");
});
  ● Gets a code and renders it in a new route

    expect(element).toHaveValue(12345)

    Expected the element to have value:
      12345
    Received:
      5

【问题讨论】:

  • 如果您使用的是 userEvent,我认为您可以放弃该行为。你能告诉我们你的 App 组件代码吗?
  • 我确实放弃了 userEvent,现在我的测试通过了,但我不断收到有关将用户事件包装在实际中的警告。我能做些什么来阻止这个警告?关于发布我的应用程序代码 Stack Overflow 不允许我发布代码,因为它说我应该添加更多细节和更少的代码。
  • 我现在正面临完全相同的问题,你们每个人都找到了解决方案@medicengonzo 吗?似乎这里也在讨论这个问题github.com/testing-library/user-event/issues/387
  • @Hylle 刚刚发布了一个答案,如果您仍然遇到问题,这可能会有所帮助
  • 谢谢@max 我会在某个时候尝试一下,尽管我最终用一个 hacky userEvent.type("example", { delay: 1}) 修复它

标签: javascript reactjs jestjs react-testing-library


【解决方案1】:

您的问题可能在于更改处理程序的实现。我最近遇到了类似的问题,这是我认为会起作用的方法,而不是真正起作用的方法。 More info at this github comment.

function handleChange(ev: FormEvent, key = "") {
  ev.preventDefault();

  // ✅ Passes
  const value = (ev.target as HTMLInputElement).value;

  setState(s => {
    // ❌ Fails (individual characters instead of progressively built up strings)
    // const value = (ev.target as HTMLInputElement).value;

    return { ...s, [key]: value };
  });
}

【讨论】:

    猜你喜欢
    • 2013-04-25
    • 2013-07-16
    • 2012-10-07
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多