【问题标题】:How can I mock react-native-webview reload function?如何模拟 react-native-webview 重新加载功能?
【发布时间】:2022-06-21 14:44:20
【问题描述】:

我正在尝试为我拥有 WebView 的组件创建单元测试。

问题是在这个组件内部我调用了 WebView 的 reload() 函数。

当我运行测试时,我得到了这个错误:

 Invariant Violation: nodeHandle expected to be non-null

      107 |     useCallback(() => {
      108 |       if (navigation.getState().index === 0) {
    > 109 |         webviewRef.current.reload();
          |                            ^
      110 |       }
      111 |     }, [webviewRef, navigation])
      112 |   );

我尝试按照我在 Jest 网站上找到的示例以这种方式模拟 reload() 函数:

jest.mock('react-native-webview', () => {
  const RealComponent = jest.requireActual('react-native-webview');
  RealComponent.reload = jest.fn();
  return RealComponent;
});

但我收到了完全相同的错误消息。看来开玩笑没有选择我的模型。

如何模拟 WebView 的 reload() 函数?

【问题讨论】:

    标签: react-native jestjs react-native-testing-library


    【解决方案1】:

    你可以试试creating a Node module mock of react-native-webview

    假设一个组件TestComponent.tsx

    import React, { useEffect, useRef } from 'react'
    import { WebView } from 'react-native-webview'
    
    export const TestComponent = () => {
      const webViewRef = useRef<WebView>(null)
    
      useEffect(() => {
        webViewRef.current?.reload()
      }, [])
    
      return <WebView ref={webViewRef} source={{ uri: `https://stackoverflow.com` }} />
    }
    

    __mocks__/react-native-webview.tsx 我们可以有这个:

    import React, { forwardRef, useImperativeHandle } from 'react'
    import { View } from 'react-native'
    
    export const refFunctions = {
      reload: jest.fn(),
    }
    
    export const WebView = forwardRef((_props, ref) => {
      useImperativeHandle(ref, () => refFunctions)
      return <View />
    })
    

    此组件的测试可能如下所示:

    import React from 'react'
    import { render } from '@testing-library/react-native'
    import { refFunctions } from '__mocks__/react-native-webview'
    import { TestComponent } from './TestComponent'
    
    describe('TestComponent', () => {
      afterEach(jest.clearAllMocks)
      it('reloads webview when component mounts', () => {
        render(<TestComponent />)
        expect(refFunctions.reload).toHaveBeenCalledTimes(1)
      })
    })
    

    【讨论】:

      猜你喜欢
      • 2022-11-11
      • 1970-01-01
      • 2020-12-11
      • 2021-10-13
      • 2021-05-10
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      相关资源
      最近更新 更多