Home >Web Front-end >JS Tutorial >How to Test stopPropagation() in React Testing Library
stopPropagation()
in ReactCorrectly implementing stopPropagation()
is vital when dealing with nested click events in React. Instead of directly verifying stopPropagation()
's call, focus on testing its outcome: does the event propagate or not?
This article compares two approaches:
✅ Testing the effect of stopPropagation()
(event propagation).
✅ Mocking the stopPropagation()
method.
✅ Determining which method is superior and when to use each.
The optimal method tests stopPropagation()
's effect by wrapping the component within a parent <div>
with an onClick
handler. We then check if the event bubbles up to the parent.
Example: Preventing Propagation
<code class="language-javascript">import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { FormElementsList } from "@/components/FormElementsList"; it("prevents event propagation on click", async () => { const onOuterClick = jest.fn(); render( <div onClick={onOuterClick}> <FormElementsList /> </div> ); const textInputElement = screen.getByText("Text Input"); await userEvent.click(textInputElement); expect(onOuterClick).toHaveBeenCalledTimes(0); // Event propagation prevented });</code>
Why This Works:
<div>
's onClick
handler (onOuterClick
) acts as a listener.stopPropagation()
functions correctly within FormElementsList
, clicking an element shouldn't trigger onOuterClick
.expect(onOuterClick).toHaveBeenCalledTimes(0)
confirms successful event prevention.stopPropagation()
Alternatively, you can directly verify stopPropagation()
's call by mocking the event and tracking the function call.
Example: Mocking stopPropagation()
<code class="language-javascript">import { render, screen } from "@testing-library/react"; import { FormElementsList } from "@/components/FormElementsList"; it("calls stopPropagation() on click", async () => { render(<FormElementsList />); const textInputElement = screen.getByText("Text Input"); const event = new MouseEvent("click", { bubbles: true }); jest.spyOn(event, "stopPropagation"); textInputElement.dispatchEvent(event); expect(event.stopPropagation).toHaveBeenCalled(); });</code>
Why This Works:
jest.spyOn(event, "stopPropagation")
monitors the function call.dispatchEvent(event)
manually triggers the click.expect(event.stopPropagation).toHaveBeenCalled()
ensures stopPropagation()
's execution.Method | Pros | Cons | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Testing Event Propagation | Tests actual user behavior | Doesn't directly confirm
|
|||||||||
Mocking | Directly confirms call | Tests implementation, not behavior |
RecommendationstopPropagation()
The above is the detailed content of How to Test stopPropagation() in React Testing Library. For more information, please follow other related articles on the PHP Chinese website!