首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在componentDidMount中测试eventListener

在componentDidMount中测试eventListener
EN

Stack Overflow用户
提问于 2019-03-13 22:54:35
回答 1查看 658关注 0票数 1

我有一个监听Linking url事件的react-native组件。如何使用react-native-testing-library触发该事件

示例:

代码语言:javascript
复制
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() {
     // ....
   }
}
EN

回答 1

Stack Overflow用户

发布于 2019-09-19 05:30:44

为了解决这个问题,我在测试文件中手动模拟了测试深度链接的Linking模块。

代码语言:javascript
复制
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));
    }),
  };
});

然后,我手动发出给定测试的事件。

代码语言:javascript
复制
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模块的更新。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55144866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档