0

LauoutContext.js为我的应用程序需求创建了一个。还使用 router位置来获取 URL/路径名。并将减速器传递给孩子。

JS 文件: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

测试文件: 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:类型无效——需要一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。

我怎样才能测试这个上下文?

这里 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
4

1 回答 1

0

这里如何模拟useHistoryreact-router-dom

jest.mock("react-router-dom", () => ({
  ...jest.requireActual("react-router-dom"),
  useLocation: () => ({
    pathname: "/",
  }),
}))

或者你需要用 BrowserRouter 包装你的组件:

<LayoutContext.Provider value={null}>
 <BrowserRouter>
    <Dashboard />
 </BrowserRouter>
</LayoutContext.Provider>
于 2020-08-06T07:01:02.670 回答