Arp
Arp

Reputation: 1088

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.

I have tried using fireEvent.input fireEvent.change, userEvent.type and nothing works.

It seems that when I use a default value the testing library does not accept changes, even though it works on production...

Any hints?

Using:

Upvotes: 0

Views: 4000

Answers (1)

Giorgio
Giorgio

Reputation: 2277

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.

Explicitly setting the input value through JS makes your test pass:

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.

Upvotes: 2

Related Questions