我有一个正在收听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() {
// ....
}
}
为了解决此问题,我手动嘲笑了测试深链接的测试文件中的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));
}),
};
});
i然后手动发射了给定测试的事件。
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 Antial的更合适和适应性的解决方案。我只需要关注任何Linking
模块更新。