【问题标题】:Getting Jest error TypeError: Cannot read properties of undefined (reading 'match') when using useParams in the component?获取 Jest 错误 TypeError:在组件中使用 useParams 时无法读取未定义的属性(读取“匹配”)?
【发布时间】:2022-02-21 03:34:08
【问题描述】:

Jest 测试文件:

import { mount, shallow } from 'enzyme'
import Browse from '@pages/Home/Browse/index'

describe('Browse test suite', () => {
  it('Browse should render correctly', () => {
    const component = shallow(<Browse />)
    expect(component).toMatchSnapshot()
  })
})

我的组件的一部分:

interface IParamTypes {
  nodeId: string
}
const Browse = () => {
  const { nodeId } = useParams<IParamTypes>()
  .....
}

运行测试用例时出错:

● Browse test suite › Browse should render correctly

TypeError: Cannot read properties of undefined (reading 'match')

  13 | }
  14 | const Browse = () => {
> 15 |   const { nodeId } = useParams<IParamTypes>()
           ^

【问题讨论】:

    标签: reactjs react-hooks jestjs


    【解决方案1】:

    您正在尝试单独渲染您的组件,这意味着您无权访问useParams 对象。我不知道如何用 Enzyme 做到这一点,但这是它如何与测试库一起使用,我相信它也应该与 Enzyme 一起使用。

    尝试使用路由器将组件包装在测试服中,并将历史对象作为道具传递:

    import {createMemoryHistory} from 'history'
    const BrowseWithRouter = () => {
        const history = createMemoryHistory();
        return (
            <Router history={history}>
                <Browse />
            </Router>
        )
    };
    

    然后浅渲染你的新组件:

    const component = shallow(<BrowseWithRouter />)
    

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 2022-01-01
      • 2022-07-06
      • 2020-03-27
      • 2021-02-15
      • 2023-04-08
      • 1970-01-01
      • 2022-12-24
      • 2023-02-26
      相关资源
      最近更新 更多