简体   繁体   English

@testing-library/react 的默认值不会发生输入更改

[英]Input changes do not occur with default value with @testing-library/react

I have the following input:我有以下输入:

<input
        name="name"
        type="text"
        data-testid="input"
        onChange={(e) => setTypedName(e.target.value)}
        value=""
      />

the test:考试:

test.only('Should change the value of the input ', async () => {
    makeSut()
    const nameInput = sut.getByTestId('input') as HTMLInputElement
    fireEvent.change(nameInput, { target: { value: 'value' } })
    expect(nameInput.value).toBe('value')
  })

My assertion fails, as the change does not take effect, while the value remains to be ""我的断言失败,因为更改没有生效,而值仍然是""

If I remove value="" from the input , change takes effect.如果我从input删除value="" ,更改就会生效。

I have tried using fireEvent.input fireEvent.change , userEvent.type and nothing works.我曾尝试使用fireEvent.input fireEvent.changeuserEvent.type ,但没有任何效果。

It seems that when I use a default value the testing library does not accept changes, even though it works on production...似乎当我使用默认value ,测试库不接受更改,即使它适用于生产......

Any hints?任何提示?

Using:使用:

  • jest 27.3.1开玩笑 27.3.1
  • @testing-library/react 12.1.2 @testing-library/react 12.1.2
  • @testing-library/user-event 13.5.0 @testing-library/user-event 13.5.0

I'm not sure, but perhaps this is due to React relying more on explicitly setting the value of components through JS rather than through "vanilla" HTML.我不确定,但这也许是因为 React 更依赖于通过 JS 而不是通过“vanilla”HTML 显式设置组件的值。

Explicitly setting the input value through JS makes your test pass:通过 JS 显式设置输入值使您的测试通过:

import { render, screen } from "@testing-library/react";
import React, { useState } from "react";
import userEvent from "@testing-library/user-event";

const Component = () => {
  const [value, setValue] = useState("");
  return (
    <input
      name="name"
      type="text"
      data-testid="input"
      onChange={(e) => setValue(e.target.value)}
      value={value}
    />
  );
};

test.only("Should change the value of the input ", async () => {
  render(<Component />);
  const nameInput = screen.getByTestId("input") as HTMLInputElement;
  userEvent.type(nameInput, "value");
  expect(nameInput.value).toBe("value");
});

PS I slightly modified your test to use render because I'm not sure what makeSut is, and I assume it's some custom function that you created to render your component. PS 我稍微修改了您的测试以使用render因为我不确定makeSut是什么,并且我假设它是您为渲染组件而创建的一些自定义函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM