反应测试库+路由器

时间:2020-09-22 22:38:45

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

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

例如,这是我的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,
  }
}

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

我做错什么了吗?

1 个答案:

答案 0 :(得分:0)

反应测试不一致的用户帮助我确定了问题。

如果任何人都遇到此问题,则是有关路由器及其放置位置的问题。 由于某些原因,路由器直接放置在number_of_rows + 1文件上,而不是# simpler version - we can skip the diffs and just get the deltas, and store all 3 colors in a list deltas=[(target_color[i] - initial_color[i])/number_of_rows for i in range(3)] for j in range(0, number_of_rows): interpolated_color=tuple([initial_color[i] + (deltas[i] * j) for i in range(3)]) print(interpolated_color) 上。

这是将路由器放入app.js的正确方法

index.js

index.js文件应该类似于

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

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

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