・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); }); });
當我傳遞一個 props 時,在本例中它是initialCount(=10),我加入了一個屬性,即initialProps: {initialCount: 10 }。
當我測試自訂鉤子的函數(在本例中為increment())時,我使用該行為並在回調中呼叫increment()。
・成功
・失敗
・顯示動作
以上是React 基礎~單元測試/自訂鉤子的詳細內容。更多資訊請關注PHP中文網其他相關文章!