【问题标题】:How to test function which returns a random React component in Jest如何测试在 Jest 中返回随机 React 组件的函数
【发布时间】:2020-02-27 12:35:48
【问题描述】:

我正在尝试测试一个从数组中返回随机选择的 React 组件的函数。 Bellow,我有一个数组,其中填充了不同类型的 React 组件。

collectionOfComponents = [
  <Component1 />
  <Component2 />
  <Component3 />
  <Component4 />
  <Component2 />
  <Component3 />
  ...
];

然后我有一个函数,它将从数组中选择一个随机组件并返回该组件,如下所示。

export default () => {
  const totalNumberOfComponents = collectionOfComponents.length;
  const randomComponentIndex = Math.floor(Math.random() * totalNumberOfQuestions);
  const randomComponent = collectionOfComponents[randomComponentIndex];

  return cloneElement(randomComponent);
};

我正在尝试编写一个单元测试来涵盖此功能,但是,由于随机返回的 React 组件并不像我想象的那么简单。

我试图模拟函数的返回,但这并没有涵盖 jests 覆盖率报告中函数的所有行。以下是我尝试过的。

jest.mock('common/services/functionName', () => "Random Component");

it('should return random React component', () => {
  expect(functionName).toEqual('Random Component');
});

【问题讨论】:

  • 你在测试什么?为了报道而报道是没有意义的。 ----- 这里你无法控制随机性,所以你不能真正测试它。您可能想要注入随机生成器,因此在运行测试之前对其进行设置。比如,如果rand() 生成1 然后返回Component 1 等等。----您也可以多次运行该函数并断言您得到不同的结果,但这意味着您更多地测试Math.randoom() 而不是比你的代码。
  • 好吧,理想情况下,我想测试一下函数是否返回了 React 组件,不管是什么类型。在阅读了 Enzyme API 文档后,我决定使用下面的方法。您的What are you testing? 问题让我想到了我真正想要测试的内容,这为我指明了以下方向。

标签: reactjs jestjs


【解决方案1】:

在考虑了如何在没有任何模拟的情况下测试函数之后,我决定使用以下方法,将我的函数包装在 div 容器中,并检查包装器是否包含 collectionOfComponents 数组中的任何组件。

it('should return random React component', () => {
  const wrapper = shallow(
    <div>
      {functionName()}
    </div>
  );

  expect(wrapper.containsAnyMatchingElements([
    ... collectionOfComponents,
  ])).toEqual(true);
});

我决定使用containsAnyMatchingElements。以下是 Enzyme API 文档的说明。

返回patternNodes 中的至少一个给定反应元素是否与包装器渲染树中的元素匹配。 patternNodes 的一个或多个元素必须匹配一次或多次。匹配遵循 containsMatchingElement 的规则。

【讨论】:

    猜你喜欢
    • 2018-03-24
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 2011-02-06
    • 2018-04-25
    • 1970-01-01
    相关资源
    最近更新 更多