首页 > 解决方案 > 下一个 router.useRouter 甚至不是一个模拟 RouterContext 的函数

问题描述

我正在尝试测试一个使用useRouterfrom next/routerhook 来获取的组件route,但即使是模拟 RouterContext,我也会收到以下错误:

Error: Uncaught [TypeError: (0 , _router.useRouter) is not a function]

我的应用程序使用redux,它也被react-redux Providerand模拟mockStore

这是我渲染组件的实用程序代码:

const getCustomWrapper =
  (router, initialState) => {
    const Wrapper = ({ children }) => {
      const store = mockStore({
        ...initialStateModel,
        ...initialState
      })

      return (
        <Provider store={store}>
          <RouterContext.Provider value={{ ...mockRouter, ...router }}>
            {children}
          </RouterContext.Provider>
        </Provider>
      )
    }

    Wrapper.propTypes = {
      children: PropTypes.node
    }

    return Wrapper
  }

const customRender = async (ui, { options, router, initialState } = {}) => {
  const Wrapper = getCustomWrapper(router, initialState)

  return render(<Wrapper>{ui}</Wrapper>, options)
}

我的测试是这样的:

const createComponent = (props = defaultProp, initialState = defaultInitialState) => {
    customRender(<MyComponet {...props} />, { initialState })
}


it('should render my text', async () => {
    createComponent()

    const myText = screen.getByText('my text')

    expect(myText).toBeInTheDocument()
})

版本

next: 10.1.2,
react-redux: 7.2.5,
react: 16.13.1

更新它现在不是一个选项=/

提前谢谢

标签: javascriptreactjsreact-reduxjestjs

解决方案


推荐阅读