首页  >  文章  >  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