Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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' }
      ]
    )
  };
like image 279
Yossi Avatar asked Apr 21 '26 02:04

Yossi


1 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'))
}));
like image 146
Ade Crown Avatar answered Apr 23 '26 19:04

Ade Crown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!