stopPropagation()
adalah penting apabila berurusan dengan peristiwa klik bersarang di React. Bukannya mengesahkan panggilan langsung stopPropagation()
, fokus pada ujian hasilnya: adakah acara menyebarkan atau tidak? stopPropagation()
✅ Menguji kesan
(penyebaran peristiwa). stopPropagation()
. stopPropagation()
Pendekatan Terbaik: Ujian Penyebaran Acara
dengan membungkus komponen dalam ibu bapa stopPropagation()
dengan pengendali <div>
. Kami kemudian menyemak sama ada peristiwa gelembung sehingga ibu bapa. onClick
Contoh
: Mencegah penyebaran
<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>
Kenapa ini berfungsi:
<div>
handler (onClick
onOuterClick
jika stopPropagation()
. FormElementsList
onOuterClick
expect(onOuterClick).toHaveBeenCalledTimes(0)
stopPropagation()
Sebagai alternatif, anda boleh mengesahkan panggilan langsung
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>
memantau panggilan fungsi.
jest.spyOn(event, "stopPropagation")
secara manual mencetuskan klik. dispatchEvent(event)
Memastikan expect(event.stopPropagation).toHaveBeenCalled()
stopPropagation()
memilih kaedah yang betul 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 |
. stopPropagation()
Atas ialah kandungan terperinci Cara Menguji Stoppropagation () di Perpustakaan Ujian React. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!