How to simulate android back button in react-native test

落爺英雄遲暮 提交于 2019-12-24 07:14:09

问题


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', () => {...})
  }
}

回答1:


There are a couple ways you can approach this:

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.

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

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.



来源:https://stackoverflow.com/questions/44952284/how-to-simulate-android-back-button-in-react-native-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!