- When I test a custom hook component, I use a renderHook imported from
@testing-library/react' and an act imported from
react-dom/test-utils'.
・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);
});
});
When I pass a props, in this case it is initialCount(=10), I add a property which is
initialProps: { initialCount: 10 }
.When I test a function of the custom hook, in this case the increment(), I use the act and call the increment() inside the callback.
Top comments (0)