我有一个监听Linking url事件的react-native组件。如何使用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() {
// ....
}
}发布于 2019-09-19 05:30:44
为了解决这个问题,我在测试文件中手动模拟了测试深度链接的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模块的应用程序接口,我的模拟将隐藏这些更新的任何冲突,并且我的测试将导致误报。然而,我找不到一个使用Jest和React Native的更合适和更具适应性的解决方案。我只需要密切关注Linking模块的更新。
https://stackoverflow.com/questions/55144866
复制相似问题