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中文網其他相關文章!