react-navigation 5 - how to test navigation event listeners using Enzyme + Jest (react native)

Viewed 246

I have implemented a focus listener in my component like so (as shown in the react-navigation v5 documentation):

componentDidMount() {
  const { navigation } = this.props
  this._unsubscribeFocus = navigation.addListener('focus', () => {
    // do something
  })
}

I am struggling with finding a way to write a unit test for this using Jest/ Enzyme. I have tried using wrapper.simulate('focus') however, this doesn't seem to make the callback run.

Does anyone have any ideas/ experience with testing this?

1 Answers

Not the best approach but let's try

focusCallback = () => {
    // do something
  }
componentDidMount() {
  const { navigation } = this.props
  this._unsubscribeFocus = navigation.addListener('focus', focusCallback)
}

// test file

wrapper.instance().focusCallback();

however this will still not cover below line

  this._unsubscribeFocus = navigation.addListener('focus', focusCallback)
Related