React 测试库:如何测试包含 useLocation() 的组件?

时间:2020-12-20 05:54:40

标签: reactjs testing react-router react-testing-library redwoodjs

我正在使用 RedwoodJS,它在后台使用 React 和 React 测试库。由于 useLocation() 钩子,我正在努力测试一个组件(以及在树中包含此组件的所有页面组件)。

在我的组件中使用 useLocation() 钩子时,我需要使用模拟浏览器位置历史记录的路由器包装我的测试组件以防止错误 Error: Uncaught [TypeError: Cannot read property 'pathname' of undefined]

但是,当我这样做时,导航组件不再完全呈现,因此我无法对其进行测试......有任何想法吗?

Navigation.js

//import statements

const renderListItems = (pathname) => {
  const NavigationItems = [{..},{..},{..}] // example

  return NavigationItems.map((item) => {
    const selected = pathname.indexOf(item.path) ? false : true
    return (
      <ListItem
        button
        key={item.text}
        onClick={() => {
          navigate(item.route)
        }}
        selected={selected}
      >
        <ListItemText primary={item.text} />
      </ListItem>
    )
  })
}

const Navigation = () => {
  const { pathname } = useLocation() // this is why I need to wrap the Navigation component in a router for testing; I'm trying to get the current pathname so that I can give a specific navigation item an active state.

  return (
    <List data-testid="navigation" disablePadding>
      {renderListItems(pathname)}
    </List>
  )
}

export default Navigation

Navigation.test.js

import { screen } from '@redwoodjs/testing'
import { renderWithRouter } from 'src/utilities/testHelpers'

import Navigation from './Navigation'

describe('Navigation', () => {
  it('renders successfully', () => {
    expect(() => {
      renderWithRouter(<Navigation />)
    }).not.toThrow()
  })
  it('has a "Dashboard" navigation menu item', () => {
    renderWithRouter(<Navigation />)
    expect(
      screen.getByRole('button', { text: /Dashboard/i })
    ).toBeInTheDocument()
  })
})

testHelpers.js

这是防止 Navigation.js 中的 useLocation() 破坏测试所必需的。

import { Router, Route } from '@redwoodjs/router'
import { createMemoryHistory } from 'history'
import { render } from '@redwoodjs/testing'
const history = createMemoryHistory()

export const renderWithRouter = (Component) =>
  render(
    <Router history={history}>
      <Route component={Component} />
    </Router>
  )

导致错误

Navigation › has a "Dashboard" navigation menu item

TestingLibraryElementError: Unable to find an accessible element with the role "button"

    There are no accessible roles. But there might be some inaccessible roles. If you wish to access them, then set the `hidden` option to `true`. Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole

    <body>
      <div />
    </body>

0 个答案:

没有答案
相关问题