【发布时间】:2019-08-06 22:30:03
【问题描述】:
我有一个无状态组件:
export default function TripReportFooter(props) {
const { tripReport, user, toggleFavorite, navigation } = props;
handleShare = async slug => {
try {
const result = await Share.share({
message: `Check out this Trip Report:\n/p/${slug}/`
});
if (result.action === Share.sharedAction) {
if (result.activityType) {
} else {
// shared
}
} else if (result.action === Share.dismissedAction) {
}
} catch (error) {
alert(error.message);
}
};
handleFavorite = async id => {
const token = await AsyncStorage.getItem("token");
toggleFavorite(id, token);
};
return (
... // handleFavorite and handleShare called with TouchableOpacities.
);
}
它内部有两个函数,handleShare 和 handleFavorite。我想测试这些函数被调用了,还有handleFavorite调用了prop函数toggle favorite。
我试过wrapper.instance().handleFavorite(),但由于它是一个无状态组件,它返回null。
接下来 Stack Overflow 上的某个人建议使用这样的间谍:
wrapper = shallow(<TripReportFooter {...props} handleFavorite={press} />);
wrapper
.find("TouchableOpacity")
.at(0)
.simulate("press");
expect(press.called).to.equal(true);
但这返回了
'TypeError: 无法读取属性'equal' of undefined'。
调用这些函数的正确方法是什么?
【问题讨论】:
-
不是答案,只是观察到您得到了
TypeError: Cannot read property 'equal' of undefined,因为.to.equal(true)是Chai语法。由于您使用的是Jest,它应该是.toBe(true)。 -
你能把你的测试用例贴在这里codesandbox.io/s/m50o1ok8o9并发回网址吗?
-
不需要先获取实例吗?包装器。实例()?不确定。这就是我在类组件上测试函数的方式,但是我在函数式组件中遇到了问题,因为它们显然没有暴露出来。
-
这两个函数是如何触发的?请编辑您的帖子,添加更多代码
标签: reactjs react-native jestjs enzyme