首頁  >  文章  >  web前端  >  React 基礎~單元測試/自訂鉤子

React 基礎~單元測試/自訂鉤子

Linda Hamilton
Linda Hamilton原創
2024-11-01 11:06:02844瀏覽
  • 當我測試自訂鉤子元件時,我使用從@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 />
    </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 Basics~unit test/custom hook

・失敗
React Basics~unit test/custom hook

・顯示動作
React Basics~unit test/custom hook

以上是React 基礎~單元測試/自訂鉤子的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn