问题
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