如何使用玩笑和(react-)测试库测试浏览器后退按钮行为?

时间:2019-12-10 14:26:20

标签: reactjs jestjs react-testing-library

我正在开发一个React应用,使用Jest和Testing Library进行测试。我想测试一下用户单击浏览器的后退按钮时会发生什么。那有可能吗?我知道我可以使用赛普拉斯,但我希望避免将其添加到我的项目中。

1 个答案:

答案 0 :(得分:0)

如果您使用的是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}>