reactjs - 如何使用 JEST、Enzyme 在 React 中测试自定义钩子(Hook)?

标签 reactjs unit-testing jestjs react-hooks enzyme

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

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

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

  return sum;
}
我在我的 funcionat 组件中使用它
const MyFuncComp = () => {
  const sum = useSum(1, 2);
  return (
   <div>{sum}</div>
  );
}
在测试用例中,我有这样的
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”。接收到的值总是“未定义”;

最佳答案

我推荐你使用:@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);    
  });
})
此外,我认为您不需要 enzyme 或任何库来测试您的组件,您可以使用 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");
  });
});

关于reactjs - 如何使用 JEST、Enzyme 在 React 中测试自定义钩子(Hook)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65039773/

相关文章:

java - 单元测试什么

c++ - 使用带有 `make check` 的 Boost 单元测试框架 (UTF)

reactjs - 开 Jest : react-router tests returns undefined 'params'

Angular 单元测试无法读取未定义的属性

javascript - 在 React 中重置子组件中的选项卡

javascript - Momentjs 弃用错误和不同的浏览器功能

reactjs - 当数据加载到 useState 中时,我的组件在页面加载后动画

javascript - 使用 sinon 为 POST 请求模拟获取 API,为 react.js 应用程序开 Jest

javascript - Jest 模拟内部函数

javascript - 按 "enter"键时停止 VSCode 触发建议