How would you mock 'onPress' within a third party library

随声附和 提交于 2019-12-24 19:29:46

问题


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()

来源:https://stackoverflow.com/questions/54435094/how-would-you-mock-onpress-within-a-third-party-library

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