How to get React Testing Library's userEvent to type into an input
Asked Answered
A

1

9

I can successfully implement a test with React Testing Library's fireEvent method, but when I try equivalent tests with userEvent I can't get it to trigger anything. How can I fix this?

CodeSandbox

/MyInput.tsx

import { useState } from "react";

export default function MyInput() {
  const [inputTextState, setInputTextState] = useState("");
  return (
    <div>
      <label>
        My Input
        <input
          value={inputTextState}
          onChange={(event) => setInputTextState(event.target.value)}
        />
      </label>
      <p>{inputTextState}</p>
    </div>
  );
}

__tests__/MyInput.test.tsx

import { fireEvent, render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import MyInput from "../MyInput";

const setup = () => {
  const utils = render(<MyInput />);
  const input = utils.getByLabelText("My Input") as HTMLInputElement;
  return {
    input,
    ...utils
  };
};

test("Simply input a number with fireEvent", () => {
  const { input } = setup();
  fireEvent.change(input, { target: { value: "23" } });
  expect(input.value).toBe("23");
});

test("Try userEvent", () => {
  const { input } = setup();
  userEvent.type(input, "23");
  expect(input.value).toBe("23");
});

Achaean answered 5/5, 2022 at 8:35 Comment(2)
Have you seen this in the react testing library docs? It looks it's returning promise, so probably you'll have to await for it to be resolvedDeweydewhirst
Yeah that was exactly the issue. Thanks.Achaean
A
14

It was simply that I needed to add async and await:

test("Try userEvent", async () => {
  const { input } = setup();
  await userEvent.type(input, "23");
  expect(input.value).toBe("23");
});

The @testing-library/user-event at v13 didn't return a promise, but the update to v14 does. At the moment, create-react-app provides v13, so it doesn't match the latest documentation. Quite confusing for the uninitiated!

Achaean answered 5/5, 2022 at 8:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.