react-native - 开 Jest/ native react : replacing/disbaling Linking. catch

标签 react-native jestjs

无法测试以下 react-native 代码。

我想做的是用我的模拟代码替换 Linking.openURL 和 Linking.OpenURL.catch。

我正在为 Linking.openURL 做如下:

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

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

但我不断得到:

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

知道如何替换/禁用 catch 子句吗?
这是我的代码:

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' }
      ]
    )
  };

最佳答案

以防万一有人收到错误信息 Cannot find module 'Linking' from

只需将 Linking 替换为 react-native/Libraries/Linking/Linking

所以你的代码应该是这样的:

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

关于react-native - 开 Jest/ native react : replacing/disbaling Linking. catch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54170367/

相关文章:

css - FlatList 的最后一项从底部修剪掉

facebook - 如何在 React Native 中使用 Facebook Messenger 对话框?

reactjs - 从 'react' 找不到模块 'pure.js' ?

chromium - 在 Jest 中使用 puppeteer 上传文件

jestjs - Babel7 Jest 意外 token 导出

typescript - Typescript 中 Jest 中默认导出类的模拟方法

javascript - 使用 Jest 时如何访问外部 javascript 方法/对象?

javascript - 在react-native中在headerRight上添加多个按钮

reactjs - 阻止 FlowType 检查 node_modules 中的错误

javascript - 如何确保在 Firebase 查询填充数组后调用 setState?