react router测试从非home开始

react router test starts from non-home

我正在测试我的 App 组件,在第一个测试中,它从家里开始,我必须点击饮料预览才能获得食谱。然而,在接下来的测试中,应该遵循相同的步骤来获取食谱,我得到了错误

Unable to find an element by: [data-testid="drink-preview"]

我开始意识到这是因为它似乎已经从食谱开始,所以它不会呈现主页以供其单击饮料预览。 只是为了确保我复制粘贴了从家里进行的完全相同的测试 -> 单击“饮料预览” -> 配方,肯定是第二次,它有同样的问题。错误日志显示它正在直接呈现食谱而不是主页,因此无法找到 drink-preview 来点击它。

test('should contain default texts in recipe -HOW TO MIX etc.', () => {
  
  const { container, getAllByTestId, getByTestId } = renderWithRouterRedux(<App />)
  
  fireEvent.click(getAllByTestId('drink-preview')[0])
  
  expect(container).toHaveTextContent('HOW TO MIX')
  expect(container).toHaveTextContent('Glass')
  expect(container).toHaveTextContent('Method')
  expect(container).toHaveTextContent('Garnish')
})
export const renderWithRouterRedux= (component, { initialState, store = createStore(reducer, initialState) } = {}) => {
  const history = createMemoryHistory()
  return {
    ...render(<Provider store={store}>
      <Router history={history}>
        {component}
      </Router>
    </Provider>),
    store,
  }
}

为什么会出现这种行为?

问题似乎是在我的 testng 中,我在两个级别的 BrowserRouter 中渲染了我的 {component} 应用程序;测试级别并作为 App 组件的第一个子组件。

原创

//App component
<div className="App" data-testid="app">
 <BrowserRouter>
      <Switch>
        <Route path="/">
          <SomeComponent/>
        </Route>
      </Switch>
    </BrowserRouter>
</div>

//index.js
ReactDOM.render(
  <Provider store={store}>
      <App />
  </Provider>,
  document.getElementById('root')
)

在已经有 BrowserRouter 的 App 组件之上,我再次在 Router 中渲染测试文件,这是不必要的。

解决方案是将这也允许我在测试中使用 a 来安全地包装应用程序组件

解决方案

//App component
<div className="App" data-testid="app">
    <Switch>
        <Route path="/">
          <SomeComponent/>
        </Route>
    </Switch>
</div>

//index.js
ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
)

This Rithm School video about testing React-Router gave me the eureka