・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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号