【问题标题】:@cypress/react : How to launch a component under a given path / URL?@cypress/react:如何在给定路径/URL 下启动组件?
【发布时间】:2021-03-22 10:31:35
【问题描述】:

我有一个 React 组件“Foo”,它使用 react-router 来决定挂载哪个子节点。

假设这个组件有 3 个子模块:A、B、C。

在“正常”的柏树测试中,我会使用 cy.visit('www.test.com/foo/subModuleA'),然后我会得到我的网站,它会显示我的 Foo 组件,这将呈现模块' A'。

但是我的组件测试直接挂载了这个组件,而 cy.visit(...) 不起作用。

不允许来自组件规范的 cy.visit 见https://github.com/bahmutov/@cypress/react/issues/286

(遗憾的是,此链接无处可去)

暂时我给自己写了一个辅助组件:

function PathEnforcer (props: React.PropsWithChildren<{ path: string }>) {

  const history = useHistory()
  useEffect(() => {
     history.push(props.path)
  }, [])

  return <>{props.children}</>
}

这只是在安装后立即切换路径。

现在我可以在我的测试中做这样的事情了:

mount(
    <HashRouter>
      <PathEnforcer path='subModuleA'>
        <Foo />
      </PathEnforcer>
    <HashRouter>
)

我的组件正在显示正确的模块。

这是我可以使用的解决方法,但它很难成为长期的最佳实践。

在给定正确路径的情况下,如何配置测试/执行直接挂载此组件的命令?

【问题讨论】:

    标签: reactjs testing cypress


    【解决方案1】:

    我遇到了同样的问题,这个问题出现了。使用 react-router v6 可以:

    mount (
      <MemoryRouter initialEntries={['/foo']}>
        <Routes>
          <Route path={'/:segment'} element={<YourComponent />}>
        </Routes>
      </MemoryRouter>
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-05
      • 2021-04-27
      • 2021-04-22
      • 1970-01-01
      • 2012-02-24
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多