testing-library / testing-library/user-event
userEvent.type does not work when setState uses previous value in assignment
Nobody has claimed this yet.
- Dominant language
- TypeScript
- Stars
- 2.3k
- Forks
- 258
- PR merge metrics
- No merged PRs in 30d
Description
Reproduction example
https://codesandbox.io/s/mystifying-jones-xpe3p2?file=/src/App.test.js:63-90
Prerequisites
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useState } from "react";
const Test = () => {
const [state, setState] = useState({ name: "" });
return (
<input
onChange={(e) => {
setState((last) => ({ ...last, name: e.target.value }));
}}
value={state.name}
/>
);
};
describe("MyInput", () => {
it("should update input", async () => {
const user = userEvent.setup();
render(<Test />);
const simpleNameTextBox = screen.getByRole<HTMLInputElement>("textbox");
await user.type(simpleNameTextBox, "test");
expect(simpleNameTextBox).toHaveValue("test");
});
});
Expected behavior
I expected the test to pass and the input being updated with "test".
Actual behavior
Output:
Expected the element to have value:
test
Received:
t
User-event version
14.4.3
Environment
Testing Library framework:
"@testing-library/react": "12.1.5",
JS framework:
"react": "17.0.2"
Test environment:
"jest": "29.4.1"
DOM implementation:
"jsdom": "20.0.0"
Additional context
I'm not sure how to configure sandbox to work so my repository example is broken but this should be enough info.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the reproduction in the linked CodeSandbox, especially src/App.test.js lines 63-90, and compare the userEvent.type call with the React state update using the previous value. Reproduce the received value of "t" under the listed React, @testing-library/react, Jest, and jsdom versions. Done means the supplied test reliably reaches the expected value of "test".
Written by the indexing model from the issue text.
Assessment
- Tech stack
- react, typescript
- Domain
- frontend, testing-qa
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100