You need to enable JavaScript to run this app. React中绑定路由与Reducer的LayoutContext单元测试及报错解决
优惠活动
大模型
产品
解决方案
定价
更多

React中绑定路由与Reducer的LayoutContext单元测试及报错解决

问题场景与现有代码实现

各文件代码

LayoutContext.js

import React, { createContext, useReducer } from 'react'
import PropTypes from 'prop-types'
import Dashboard from '../components/layouts/primary/Dashboard'
import layoutReducer from '../reducers/layoutReducer'
import { useLocation } from 'react-router-dom'

export const LayoutContext = createContext()
const LayoutContextProvider = (props) => {
  const [leftDrawerSelectedItem, layoutDispatch] = useReducer(
    layoutReducer,
    useLocation().pathname
  )
  return (
    <LayoutContext.Provider value={{ leftDrawerSelectedItem, layoutDispatch }}>
      <Dashboard>{props.children}</Dashboard>
    </LayoutContext.Provider>
  )
}

LayoutContextProvider.propTypes = {
  children: PropTypes.object
}

export default LayoutContextProvider

Dashboard.js

const Dashboard = (props) => {
  const { children } = props
  const classes = useStyles()
  let location = useLocation()

  return (
    <div className={classes.root}>
      <main className={classes.main}>{children}</main>
    </div>
  )
}

Dashboard.propTypes = {
  children: PropTypes.node
}
export default Dashboard

原有测试文件 LayoutContext.test.js

import React, { createContext, useReducer } from 'react'
import { render, fireEvent } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'

import LayoutContext from '../LayoutContext'
import Dashboard from '../Dashboard'
import LayoutContextProvider from '../LayoutContext'

test('LayoutContext test', () => {
  const tree = (
    <LayoutContext.Provider value={null}>
      <Dashboard />
    </LayoutContext.Provider>
 )

  const { getByText } = render(tree)
  expect(getByText('Something')).toBeInTheDocument()
})

报错信息

警告:React.createElement 接收到无效的组件类型——应该传入字符串(对应内置组件)、类或函数(对应自定义复合组件),但实际拿到的是undefined。通常原因是你忘记在定义组件的文件中导出组件,或是混淆了默认导入和命名导入的使用方式。

报错原因定位
  • 导入导出方式不匹配:LayoutContext是LayoutContext.js中的命名导出对象,但测试文件使用默认导入方式获取该值,实际拿到的是undefined,直接触发了组件类型无效的报错。
  • 导入路径错误:测试文件中引入的Dashboard路径为../Dashboard,但项目内实际的Dashboard组件路径是../components/layouts/primary/Dashboard,同样会导入得到undefined值。
  • 测试逻辑偏离目标:测试没有覆盖自实现的LayoutContextProvider核心逻辑,反而手动拼接了Context.Provider、传入null值,绕开了Provider内部封装的reducer初始化、路径关联逻辑。
  • 缺少必要的运行上下文:LayoutContextProvider和Dashboard组件都依赖react-router的useLocation hook,测试渲染时没有提供路由上下文,即使修正导入问题也会触发hook调用错误。
正确的Context测试实现方案
  • 修正导入规则:将命名导出的LayoutContext改为解构导入,删除无效的Dashboard导入路径(Provider内部已经引入了对应Dashboard组件,测试不需要单独引入)。
  • 模拟路由运行环境:使用MemoryRouter包裹待测试组件,满足内部useLocation hook的上下文要求,可自定义初始路由路径用于测试。
  • 增加Context消费逻辑:在Provider内部放置一个测试消费组件,通过useContext获取Context值,验证路径关联、reducer状态更新的逻辑是否符合预期。

修正后的测试代码示例

import React from 'react'
import { render } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import { MemoryRouter } from 'react-router-dom'
// 同时导入命名导出的Context、默认导出的Provider
import { LayoutContext, default as LayoutContextProvider } from '../LayoutContext'

// 测试专用的Context消费组件
const TestContextConsumer = () => {
  const contextData = React.useContext(LayoutContext)
  return <div data-testid="context-output">{contextData.leftDrawerSelectedItem}</div>
}

test('LayoutContext 能正确关联当前路由路径到全局状态', () => {
  // 模拟路由,指定测试初始路径
  const { getByTestId } = render(
    <MemoryRouter initialEntries={['/user-center']}>
      <LayoutContextProvider>
        <TestContextConsumer />
      </LayoutContextProvider>
    </MemoryRouter>
  )

  // 校验Context传递的路径值和模拟路由一致
  expect(getByTestId('context-output')).toHaveTextContent('/user-center')
})

内容的提问来源于stack exchange,提问作者Selim Reza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.12.03 15:15:03