React 基础知识~单元测试/自定义钩子
- 当我测试自定义钩子组件时,我使用从@testing-library/react'导入的renderhook和从react-dom/test-utils'导入的act。
・src/app.tsx
import "./app.css"; import counter from "./component/counter/counter"; function app() { return ( <div classname="app"> <counter></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 基础知识~单元测试/自定义钩子的详细内容,更多请关注其它相关文章!