【问题标题】:how can i test browser back-button behaviour using jest and (react-) testing-library?如何使用 jest 和 (react-) testing-library 测试浏览器后退按钮的行为?
【发布时间】:2020-04-03 18:27:45
【问题描述】:

我正在开发一个 React 应用程序,使用 Jest 和 Testing Library 进行测试。我想测试当用户单击浏览器的后退按钮时会发生什么。这可能吗?如果可以,怎么做?我知道我可以使用 Cypress,但我不想将其添加到我的项目中。

【问题讨论】:

标签: reactjs jestjs react-testing-library


【解决方案1】:

如果您使用 React Router,首先您需要访问测试中的历史对象,然后您可以调用 history.goBack()。

有几个选项可以获取历史对象:

  1. From a custom route
<Route
  path="*"
  render={props => {
     history = props.history;
     location = props.location;
     return null;
  }}
/>
  1. Using createMemoryHistory
import { createMemoryHistory } from 'history'
...
const history = createMemoryHistory()
...
<Router history={history}>

【讨论】:

    猜你喜欢
    • 2021-02-11
    • 2020-03-22
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2020-03-24
    • 2020-01-20
    • 2019-07-08
    相关资源
    最近更新 更多