stopPropagation()
中进行测试>至关重要。 而不是直接验证stopPropagation()
的呼叫,而是专注于测试其结果:事件是否传播?stopPropagation()
>
✅测试
>的效果(事件传播)。stopPropagation()
>
方法。
stopPropagation()
✅确定哪种方法是优越的,何时使用。
最佳方法:测试事件传播
>处理程序包裹在父stopPropagation()
中。 然后,我们检查事件是否起泡到父母。<div>
onClick
>
<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>
parent
<div>
)充当侦听器。onClick
>
onOuterClick
>如果stopPropagation()
>FormElementsList
>。
onOuterClick
expect(onOuterClick).toHaveBeenCalledTimes(0)
替代:嘲笑stopPropagation()
stopPropagation()
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>
监视函数调用。
jest.spyOn(event, "stopPropagation")
dispatchEvent(event)
的执行。expect(event.stopPropagation).toHaveBeenCalled()
选择正确的方法stopPropagation()
Method | Pros | Cons |
---|---|---|
Testing Event Propagation | Tests actual user behavior | Doesn't directly confirm stopPropagation() call |
Mocking stopPropagation()
|
Directly confirms stopPropagation() call |
Tests implementation, not behavior |
>
以上是如何在React测试库中测试StopPropagation()的详细内容。更多信息请关注PHP中文网其他相关文章!