如何使用Jest测试从'react-navigation-hooks'中使用useNavigation的自定义react挂钩?

时间:2020-08-25 22:43:31

标签: react-native unit-testing react-hooks

我有一个自定义的反应挂钩'useSample',它使用useNavigation和useNavigationParam

    import { useContext } from 'react'
    import { useNavigation, useNavigationParam } from 'react-navigation-hooks'
    import sampleContext from '../sampleContext'
    import LoadingStateContext from '../LoadingState/Context'

    const useSample = () => {
      const sample = useContext(sampleContext)
      const loading = useContext(LoadingStateContext)
      const navigation = useNavigation()
      const Mode = !!useNavigationParam('Mode')

      const getSample = () => {
        if (Mode) {
         return sample.selectors.getSample(SAMPLE_ID)
        }
        const id = useNavigationParam('sample')
        sample.selectors.getSample(id)
        navigation.navigate(SAMPLE_MODE_ROUTE, { ...navigation.state.params}) // using navigation hook here
       }
      return { getSample }
     
     }
      export default useSample
    

我需要使用笑话为上述钩子编写单元测试,然后尝试了以下操作

    import { renderHook } from '@testing-library/react-hooks'
    import sampleContext from '../../sampleContext'
    import useSample from '../useSample'
     
    describe('useSample', () => {
     it('return sample data', () => {
       const getSample = jest.fn()
       const sampleContextValue = ({
          selectors: {
            getSample
          }
       })
       const wrapper = ({ children }) => (
       <sampleContext.Provider value={sampleContextValue}>
       {children}
       </sampleContext.Provider>
       )
       renderHook(() => useSample(), { wrapper })
    })
  })

我得到了错误

'反应导航挂钩需要导航上下文,但找不到它。确保您没有忘记创建和呈现react-navigation应用程序容器。如果您需要访问可选的导航对象,则可以使用Context(NavigationContext),它可能会返回“

任何帮助将不胜感激!

我正在使用的版本

“ react-navigation-hooks”:“ ^ 1.1.0”
“ @ testing-library / react-hooks”:“ ^ 3.4.1”
“反应”:“ ^ 16.11.0”

2 个答案:

答案 0 :(得分:0)

您必须模拟react-navigation-hooks模块。

在测试中:

import { useNavigation, useNavigationParam } from 'react-navigation-hooks';

jest.mock('react-navigation-hooks');

由您决定向模拟添加自定义实现。如果要这样做,可以检查如何在Jest文档中模拟函数。

答案 1 :(得分:0)

对我来说,可以使用enter code here useRoute()来保存它:

对于功能组件:

import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';

function MyBackButton() {
  const navigation = useNavigation();

  return (
    <Button
      title="Back"
      onPress={() => {
        navigation.goBack();
      }}
    />
  );
}

对于课程组件:

class MyText extends React.Component {
  render() {
    // Get it from props
    const { route } = this.props;
  }
}

// Wrap and export
export default function(props) {
  const route = useRoute();

  return <MyText {...props} route={route} />;
}