React 测试库 + 路由器

React Testing Library + Router

我想在同一个测试文件中呈现不同的路线。

例如,这是我的 cooltest.test.js

import { App } from '../App.js'
import { renderWithRouter } from './renderHelper'

test('Example - Render View', async () => {

  const route = '/dummy/Seguros'
  const { getByText, getByTestId } = renderWithRouter(<App />, { route })

  getByTestId('dummyHeader');
  getByText(route)
});

test('Example - Render Another View', async () => {

  const route = '/dummy/Ayuda/Seguros'
  const { getByText, getByTestId } = renderWithRouter(<App />, {
    route
  })

  getByText(route);
});

我得到一个文件,其中包含 renderHelper.js:

export const renderWithRouter = (
  ui,
  {
    route = '/',
    history = createMemoryHistory({ initialEntries: [route] }),
  } = {}
) => {
  const Wrapper = ({ children }) => (
    <Router history={history}>{children}</Router>
  )
  return {
    ...render(ui, { wrapper: Wrapper }),
    // adding `history` to the returned utilities to allow us
    // to reference it in our tests (just try to avoid using
    // this to test implementation details).
    history,
  }
}

问题是它总是转到我的主页或 "/" 站点。

我是不是做错了什么?

react-testing discord 上的一位用户帮助我确定了问题。

如果有人遇到这个问题,那是路由器及其放置位置的问题。 由于某种原因,路由器直接放在 app.js 文件而不是 index.js.

这是在 index.js

中设置路由器的正确方法
import { App } from './App.js'

ReactDOM.render(
  <React.StrictMode>
    <Router>
      <App/>
    </Router>
  </React.StrictMode>,
  document.getElementById('root')
);

并且 app.js 文件应该类似于

function App() {
  return (
    <main>
      <Switch>
        <Route path={`${process.env.PUBLIC_URL}/`} exact component={Landing} />
        <Route path={`${process.env.PUBLIC_URL}/dummy/:number?`} component={Dummy} />
        <Route path="*" exact component={NotFound} />
      </Switch>
    </main>
  );
}

再次感谢“ljosberinn | Gerrit Alex”的帮助。