我有一个react-native
组件正在监听Linking
url事件。我将如何使用react-native-testing-library
触发该事件?
示例:
import React, { PureComponent } from 'react';
import { View, Text, Linking, ActivityIndicator } from 'react-native';
import SafariView from 'react-native-safari-view';
class WebAuthView extends Component<Props, State> {
componentDidMount() {
Linking.addEventListener('url', this.handleAuthUrl);
SafariView.addEventListener('onDismiss', this.handleDismiss);
}
componentWillUnmount() {
Linking.removeEventListener('url', this.handleAuthUrl);
SafariView.removeEventListener('onDismiss', this.handleDismiss);
}
handleAuthUrl = ({url}) => {
// Implementation goes here
}
render() {
// ....
}
}
答案 0 :(得分:0)
为解决此问题,我在测试深度链接的测试文件中手动模拟了Linking
模块。
jest.mock('Linking', () => {
const listeners = [];
return {
addEventListener: jest.fn((event, handler) => {
listeners.push({ event, handler });
}),
emit: jest.fn((event, props) => {
listeners.filter(l => l.event === event).forEach(l => l.handler(props));
}),
};
});
然后我为指定的测试手动发出事件。
it('handles deep links to content', () => {
render(<App />);
Linking.emit('url', { url: 'https://test.com/content/foo' });
expect(Link.navigateToURL).toHaveBeenCalled();
});
该方法的缺点是,如果React Native修改了Linking
模块的API,我的模拟将隐藏这些更新中的所有冲突,并且我的测试将导致误报。但是,我无法通过Jest和React Native找到更合适和更适应的解决方案。我只需要关注任何Linking
模块更新。