userEvent.type inputs only last character when wrapped in act

Viewed 2829

I found an issues in the user-event github and it says its resolved in version 12.0.1 but I'm on version 12.1.5 and I keep getting the error.

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
1 Answers

Your problem might be in the implementation of the change handler. I recently had a similar issue, and here's what I thought would work, versus what really worked. 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 };
  });
}
Related