Part 14 / Topic 2 of 7
user-event vs fireEvent
Both dispatch DOM events - the difference is how faithfully. fireEvent.change sets an input's .value directly, in one shot, then fires a single "change" event; it never consults the browser's own input-constraint machinery. user-event drives real keydown/keypress/input events one character at a time, through the same path an actual keystroke takes. examples/02_user_event_vs_fire_event.jsx's OtpInput has a plain maxLength={6}:
// examples/02_user_event_vs_fire_event.jsx
export function OtpInput() {
const [value, setValue] = useState("");
return <input aria-label="OTP" maxLength={6} value={value} onChange={(e) => setValue(e.target.value)} />;
}
fireEvent.change(input, { target: { value: "123456789" } }) really leaves the input holding all nine characters - maxLength never got a say, because nothing resembling a keystroke happened. userEvent.type(input, "123456789") really stops at six - "123456" - the same clamp a real browser applies to a real user's typing (examples/02_user_event_vs_fire_event.test.jsx). This is not a demonstration that fireEvent is "wrong" - this course has used it since stage-2-intermediate/part-07-custom-hooks/examples/06_use_debounce.test.jsx's keystroke-timing tests, where a single fireEvent.change per keystroke is exactly enough. The rule: reach for user-event by default, because it behaves the way a real user would and that is usually the thing worth testing; reach for fireEvent when you specifically want a low-level, single-event poke and nothing about realistic browser behaviour matters to that particular test.
Done here? The practice set for Part 14 — including the solutions — is on the part page.