How would you mock 'onPress' within a thir

2019-08-17 10:57发布

This question is similar to How would you mock 'onPress' within Alert?
However, since the solution given there doesn't apply in this case, I am posting this new question.

I am using an external library that provides similar functionality to react-native Alert.alert, and adds async support. The library is https://github.com/slorber/react-native-alert-async.

I am trying to mock OK / cancel events on that async alert (AlertAsync), but, as wrote above, the solution for the 'standard' react-native Alert.alert doesn't apply here.

There are two challenges here:

  • First one, similar to react-native's ALERT, mocking the OK/cancel actions
  • Second one , handling an async ALERT together with the above

Any suggestion how to do this?

Here is what I tried:

Definition

jest.mock('react-native-alert-async', () => {
      return {
        AlertAsync: jest.fn()
      }
    })

Test

Issue 1. For the following:

AlertAsync.calls[0][2][1].onPress()

I get:

TypeError: Cannot read property '0' of undefined

Issue 2. In the test I need to call (which is calling AlertAsync) first, in order to trigger AlertAsync However, since it is asynchronous I need to do 'await' for it, so is not getting called at all...

Here is a sample of the test that is not working, obviously:

expect.assertions(1)
await instance.handleCallingFunction()
AlertAsync.calls[0][2][1].onPress() // onPress Cancel

expect(<some-state>).toEqual(<expected-state>)
expect(<some-function>).toHaveBeenCalled()
expect(AlertAsync).toHaveBeenCalled()

0条回答
登录 后发表回答