jest / react-native: replacing/disbaling Linking.catch

Viewed 2442

Having trouble testing the following react-native code.

What I would like to do is to replace Linking.openURL and Linking.OpenURL.catch with my mock code.

I am doing it for Linking.openURL as following:

jest.mock('Linking', () => {
      return {
        openURL: jest.fn()
      }
    })

Linking.openURL.mockImplementation(() => true)

But I keep getting:

TypeError: _reactNative.Linking.openURL(...).catch is not a function

Any idea how to replace/disable the catch clause?
This is my code:

func1() {

    switch (this.props.a) {
      case 'NO':
        this.alertMessage(`msg`)
        break
      case 'YES':
      default:
        Linking.openURL(url1).catch(err => { Linking.openURL(url2)
        })
    }
  }

  alertMessage = (title) => {
    Alert.alert(
      title,
      '',
      [
        { text: 'OK',
          onPress: () => {
            Linking.openURL(url1).catch(err => {
              Linking.openURL(url2)
            })
          } },
        { text: 'Cancel',
          onPress: () => {
            this.setState({
              stateVar1: true
            })
          },
          style: 'cancel' }
      ]
    )
  };
2 Answers

Just in case someone gets an error with the message Cannot find module 'Linking' from

Just replace Linking with react-native/Libraries/Linking/Linking.

So your code should look something like this:

jest.mock('react-native/Libraries/Linking/Linking', () => ({
  openURL: jest.fn(() => Promise.reject('some error reason'))
}));

Linking.openURL returns a Promise, so the mock function needs to return one as well. If you want to test what happens on catch you can reject the promise (or resolve it if you don't want the catch to be called).

Here's an example for the mock with the promise rejected:

jest.mock('Linking', () => ({
  openURL: jest.fn(() => Promise.reject('some error reason'))
}));
Related