如何使用 JEST、Enzyme 在 React 中测试自定义钩子?

Pav*_*sha 5 unit-testing reactjs jestjs enzyme react-hooks

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

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

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

  return sum;
}
Run Code Online (Sandbox Code Playgroud)

我在我的 funcionat 组件中使用它

const MyFuncComp = () => {
  const sum = useSum(1, 2);
  return (
   <div>{sum}</div>
  );
}
Run Code Online (Sandbox Code Playgroud)

在测试用例中,我有这样的

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);    
  });
})
Run Code Online (Sandbox Code Playgroud)

它永远不会执行“useState”或“useEffect”。接收到的值总是“未定义”;

lis*_*tdm 5

我建议你使用: @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);    
  });
})
Run Code Online (Sandbox Code Playgroud)

此外,我认为您不需要酶或任何库来测试您的组件,您可以使用 react-dom 和 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");
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回复。但我必须使用“笑话”和“酶”进行测试。 (2认同)