DEV Community

Cover image for React Basics~unit test/custom hook
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React Basics~unit test/custom hook

  • When I test a custom hook component, I use a renderHook imported from @testing-library/react' and an act imported fromreact-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; 
Enter fullscreen mode Exit fullscreen mode

・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; 
Enter fullscreen mode Exit fullscreen mode

・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 }; }; 
Enter fullscreen mode Exit fullscreen mode

・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); }); }); 
Enter fullscreen mode Exit fullscreen mode
  • 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.

・Success
Image description

・Failure
Image description

・the display action
Image description

Top comments (0)