Rumah > Artikel > hujung hadapan web > Asas React~ujian unit/cangkuk tersuai
・src/App.tsx
import "./App.css"; import Counter from "./component/counter/Counter"; function App() { return ( <div className="App"> <Counter /> </div> ); } export default App;
・src/component/counter/Counter.tsx
import React, { useState } from "react"; import { useCounter } from "../../hooks/useCounter"; const Counter = () => { const { count, increment } = useCounter({ initialCount: 10 }); return ( <div> <h1>{count}</h1> <button onClick={() => increment()}>Increment</button> </div> ); }; export default Counter;
・src/hooks/useCounter.tsx
import React, { useState } from "react"; import { UseCounterProps } from "./useCounter.type"; type UseCounterProps = { initialCount?: number; }; export const useCounter = ({ initialCount = 0 }: UseCounterProps = {}) => { const [count, setCount] = useState(initialCount); const increment = () => setCount((prev) => prev + 1); return { count, increment }; };
・src/hooks/useCounter.test.tsx
import { renderHook } from "@testing-library/react"; import { useCounter } from "./useCounter"; import { act } from "react-dom/test-utils"; describe("useCounter", () => { test("Should render the initial count", () => { const { result } = renderHook(useCounter, { initialProps: { initialCount: 10 }, }); expect(result.current.count).toBe(10); }); test("Increment the count", () => { const { result } = renderHook(useCounter); act(() => { result.current.increment(); }); expect(result.current.count).toBe(1); }); });
Apabila saya lulus props, dalam kes ini ia adalah initialCount(=10), saya menambah property iaitu initialProps: { initialCount: 10 }.
Apabila saya menguji fungsi cangkuk tersuai, dalam kes ini kenaikan(), saya menggunakan akta dan memanggil kenaikan() di dalam panggilan balik.
・Kejayaan
・Kegagalan
・tindakan paparan
Atas ialah kandungan terperinci Asas React~ujian unit/cangkuk tersuai. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!