Home  >  Article  >  Web Front-end  >  React Basics~unit test/custom hook

React Basics~unit test/custom hook

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 11:06:02844browse
  • 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;

・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.

・Success
React Basics~unit test/custom hook

・Failure
React Basics~unit test/custom hook

・the display action
React Basics~unit test/custom hook

The above is the detailed content of React Basics~unit test/custom hook. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn