gpt4 book ai didi

reactjs - 如何测试无状态组件

转载 作者:行者123 更新时间:2023-12-03 13:35:57 25 4
gpt4 key购买 nike

我正在尝试测试下面的组件,但出现错误,它是一个带有一些数据的功能组件。

下面的组件从父组件接收信息列表并渲染,它工作得很好,但是在编写测​​试用例时,它使用 Jest 和 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 />);
});
});

错误:类型错误:无法与“未定义”或“空”匹配。

最佳答案

当您mount InfoToolTip时,您在组件中尝试解构data prop时不会传递任何 Prop :

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

所以你可以这样修复它:

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

Related question.

关于reactjs - 如何测试无状态组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49468126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com