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?
/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");
});
await
for it to be resolved – Deweydewhirst