测试历史记录.goback与测试库和反应

时间:2020-06-08 08:03:43

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

我正在尝试检查此组件中的返回导航:

class BackMore extends Component {
  render() {
    return (
      <div className="backMore">
        <div className="back" onClick={ this.props.history.goBack } data-testid="go-back">
          <FontAwesomeIcon icon={faArrowLeft} />
        </div>
        <span className="title">{ this.props.title }</span>
        <More/>
      </div>)
  }
}

export default withRouter(BackMore)

我使用testing-libraryhttps://testing-library.com/docs/example-react-router页面上的食谱

// test utils file
function 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,
  }
}

这是我的考验:

test('Go back in the history', () =>{
  const browserHistory = createMemoryHistory()
  browserHistory.push('/my-learning');
  const { history } = RenderWithRouter(<BackMore />, { route: ['my-learning'], history: browserHistory });
  userEvent.click(screen.getByTestId(/go-back/i));
  expect(history.location.pathname).toBe('/')
})

history.location.pathname变量为“我的学习”,应为“ /”

怎么了?

0 个答案:

没有答案