・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中文网其他相关文章!