中测试自定义钩子

中测试自定义钩子

本文介绍了如何使用 JEST、Enzyme 在 React 中测试自定义钩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像下面这样的自定义钩子

I have a Custom Hook like below

const useSum = (a = 1, b = 1) => {
  const [sum, setSum] = useState(a + b);

  useEffect(() => {
    setSum(a + b);
  }, [a, b]);

  return sum;
}

我在我的功能组件中使用它

I am using this in my funcionat component

const MyFuncComp = () => {
  const sum = useSum(1, 2);
  return (
   <div>{sum}</div>
  );
}

在测试用例中我是这样的

In test case I have it like this

describe('Testing MyFuncComp', () => {
  const myFuncComp = mount(<MyFuncComp />);
  it('should have value of sum', () => {

    const expected = '3';
    const received = myFuncComp.find('div').text();
    expect(received).toEqual(expected);
  });
})

它从不执行useState"或useEffect".接收到的值总是未定义";

It's never executing 'useState' or 'useEffect'. Received value is always 'undefined';

推荐答案

我推荐你使用:@testing-library/react-hooks

import { renderHook } from '@testing-library/react-hooks';


describe('Testing MyFuncComp', () => {
  it('should have value of sum', () => {
    const myFuncComp = renderHook(() => useSum(1,2));
    const expected = '3';
    const received = myFuncComp.current;
    expect(received).toEqual(expected);
  });
})

另外我认为你不需要酶或任何库来测试你的组件,你可以使用 react-dom 和 react-dom/test-utils

Also I don't think you need enzyme or any lib to test your component, you can use react-dom and react-dom/test-utils

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import MyFunComp from "./MyFunComp";

let container = null;

describe("Card component", () => {
  beforeEach(() => {
    // setup a DOM element as a render target
    container = document.createElement("div");
    document.body.appendChild(container);
  });

  afterEach(() => {
    // cleanup on exiting
    unmountComponentAtNode(container);
    container.remove();
    container = null;
  });

  it("Should render correctly", async () => {
    await act(async () => {
      render(<MyFunComp />, container);
    });
    const div = container.querySelector("div");
    expect(div).toBeTruthy();
    expect(div.textContent).toBe("123");
  });
});

这篇关于如何使用 JEST、Enzyme 在 React 中测试自定义钩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:00