【发布时间】:2018-05-27 22:12:06
【问题描述】:
编辑
当前示例,
it('CALLED THE canOpenURL FUNCTION', () => {
const wrapper = mount(<ResourceCardComponent {...mockProps} />);
const canOpenURLSpy = jest.spyOn(Linking, 'canOpenURL');
wrapper.find('TouchableOpacity').simulate('click');
expect(canOpenURLSpy).toHaveBeenCalled();
canOpenURLSpy.mockReset();
canOpenURLSpy.mockRestore();
});
错误
expect(jest.fn()).toHaveBeenCalled() 期望的模拟函数 被调用了。
问题
我正在使用Jest 和Enzyme 来测试使用React Native 制作的类。这个类里面有一个函数,当它被触发时,它使用链接库来调用canOpenUrl 和openUrl。我可以模拟已安装组件上的单击事件,但我无法知道我可以实际测试多少。
我的目标是检查Linking.canOpenUrl 是否曾经触发过。
示例
组件内部的函数是这样的,
onPressLink() {
console.log('HEY THIS FUNCTION FIRED WOOT WOOT');
Linking.canOpenURL(this.props.url).then((supported) => {
if (supported) {
Linking.openURL(this.props.url);
}
});
}
我可以像这样模拟这种发射,
describe('onPressLink has been called!', () => {
it('It clicks the mock function onPressLink!', (done) => {
const wrapper = mount(<MyComponent {...mockProps} />);
const onPressLink = jest.fn();
const a = new onPressLink();
wrapper.find('TouchableOpacity').first().simulate('click');
expect(onPressLink).toHaveBeenCalled();
done();
});
});
现在确实有效,但我的目标是使用这样的东西,
expect(Linking.canOpenUrl).toHaveBeenCalled();
但我不断收到此错误,
TypeError:无法读取未定义的属性“_isMockFunction”
当前代码试图检查这个函数是否被触发过。在使用模拟方法单击的父函数内部,
it('calls canOpenURL', () => {
const wrapper = mount(<MyComponent {...mockProps} />);
const canOpenURL = jest.spyOn(wrapper.instance, 'onPressLink');
wrapper.find('TouchableOpacity').simulate('click');
expect('Linking.canOpenUrl').toHaveBeenCalled();
});
问题
检查Linking.canOpenURL 在其父函数执行时是否被触发的正确方法是什么?
【问题讨论】:
标签: react-native jestjs enzyme