【发布时间】:2020-08-25 22:43:31
【问题描述】:
我有一个使用 useNavigation 和 useNavigationParam 的自定义反应钩子“useSample”
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
我需要使用 jest 为上面的钩子编写单元测试,我尝试了以下
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 挂钩需要导航上下文,但找不到。确保您没有忘记创建和渲染 react-navigation 应用程序容器。如果需要访问可选的导航对象,可以使用Context(NavigationContext),可能会返回'
任何帮助将不胜感激!
我正在使用的版本
“反应导航钩子”:“^1.1.0”
"@testing-library/react-hooks":"^3.4.1"
“反应”:“^16.11.0”
【问题讨论】:
标签: react-native unit-testing react-hooks