如何在 react-native 测试中模拟 android 后退按钮 [英] How to simulate android back button in react-native test

查看:48
本文介绍了如何在 react-native 测试中模拟 android 后退按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

componentDidMount 中,我添加了一个侦听器来处理 Android 后退导航,并希望围绕它的行为添加测试.我如何首先在 componentDidMount 中测试某些内容,其次我将如何模拟单击后退按钮.

In componentDidMount I'm adding a listener to handle Android back navigation and would like to add tests around it's behaviour. How do I firstly test something in componentDidMount and secondly how would I simulate clicking the back button.

class Component extends React.Component {
  componentDidMount () {
    BackHandler.addEventListener('hardwareBackPress', () => {...})
  }
}

推荐答案

有几种方法可以解决这个问题:

There are a couple ways you can approach this:

首先,您可以假设 componentDidMountBackHandler.addEventListener 将起作用.那会让你只测试你的功能.如果你走那条路,你可能想在 addEventListener 中注册一个命名函数,而不是一个箭头函数,这样你就可以在你的测试中定位它.

First, you could just assume that componentDidMount and BackHandler.addEventListener are going to work. That would leave you just testing your function. If you go that route, you'd probably want to register a named function, rather than an arrow function, in addEventListener so that you can target it in your test.

如果出于某种原因,您想测试整个生命周期,那么 Facebook 实际上有一个模拟的 BackHandler,可以让您模拟背压:

If for some reason, you want to test the full lifecycle, then Facebook actually has a mocked out BackHandler that lets you simulate a back press:

https://github.com/facebook/react-native/blob/master/Libraries/Utilities/mocks/BackHandler.js

https://github.com/facebook/react-native/blob/master/Libraries/Utilities/mocks/BackHandler.js

您只需将该模拟导入到您的测试中,将组件安装在测试渲染器中,然后触发 mockBackPress 并观察您的函数是否被调用.

You'd just need to import that mock into your test, mount the component in a test renderer and then trigger mockBackPress and watch to see if your function is called.

这篇关于如何在 react-native 测试中模拟 android 后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆