如何测试无状态组件 [英] How to test a stateless component

查看:60
本文介绍了如何测试无状态组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试以下组件,但出现错误,它是包含一些数据的功能组件.

I am trying to test below component but getting error, its a functional component with some data.

下面的组件从父组件接收信息列表并进行渲染,其工作正常,但是在编写测​​试用例时,使用笑话和酶失败了

The below component receive list of informations from parent component and renders, its work perfectly, but when writing test cases its failing using jest and enzyme

import React from "react";

export const InfoToolTip = data => {
  const { informations = [] } = data.data;

  const listOfInfo = () => {
    return informations.map((info, index) => {
      const { name, id } = info;
      return [
        <li>
          <a
            href={`someURL?viewMode=id`}
          >
            {name}
          </a>
        </li>
      ];
    });
  };

  return (
    <div className="tooltip">
        <ul className="desc">{listOfInfo()}</ul>
    </div>
  );
};

测试用例

import React from "react";
import { shallow, mount } from "enzyme";
import { InfoToolTip } from "../index.js";

describe("InfoToolTip", () => {
  it("tooltip should render properly",() => {
    const wrapper = mount(<InfoToolTip  />);
  });
});

错误: TypeError:无法与"undefined"或"null"匹配.

Error: TypeError: Cannot match against 'undefined' or 'null'.

推荐答案

当您mount InfoToolTip时,您不传递任何道具,而在组件中尝试破坏data道具:

When you mount InfoToolTip you don't pass any props while in component you try to destructure data prop:

const { informations = [] } = data.data;

所以您可以通过以下方式解决它:

So you could fix it this way:

const wrapper = mount(<InfoToolTip data={{}} />);

相关问题.

这篇关于如何测试无状态组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆