【问题标题】:How to test custom hooks in React using JEST, Enzyme?如何使用 JEST、Enzyme 在 React 中测试自定义钩子?
【发布时间】:2021-03-10 09:07:30
【问题描述】:

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

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

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

  return sum;
}

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

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
  • 问题是,'useState' 和 'useEffect' 没有被执行;并且由于它们没有被执行,“总和”总是“未定义”。
  • 对我来说它工作正常(传递上面的代码,如果我使用 const expected = '4'; 会失败),react/react-dom 为 16.12,酶为 3.10;你可以检查一下你使用的版本吗?
  • 就像我说的那样看起来不错。我只是应付并粘贴,它按预期工作:repl.it/@tmhao2005/Todo#src/Sum/index.test.tsx。您可能需要再次检查您的测试环境

标签: reactjs unit-testing jestjs react-hooks enzyme


【解决方案1】:

我建议你使用:@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

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-dom 测试您的组件,请参阅我的编辑 :)
  • 很遗憾,我无法使其易于理解。问题是“useState”和“useEffect”在测试时没有得到执行。获取 div 的文本内容没有问题。请在描述中检查我的问题。
  • 您使用的是什么版本的酶和反应?
  • 我理解你的问题,我的回答只是一个建议,我会尝试重现你的问题,但我需要知道酶和反应版本
猜你喜欢
  • 2021-07-08
  • 2021-04-17
  • 2022-01-13
  • 1970-01-01
  • 2021-12-26
  • 2019-08-02
  • 2020-08-07
  • 2021-06-07
  • 2020-01-11
相关资源
最近更新 更多