简体   繁体   English

如何使用 jest 和(react-)testing-library 测试浏览器后退按钮的行为?

[英]how can i test browser back-button behaviour using jest and (react-) testing-library?

I'm working on a React app, using Jest and Testing Library for my tests.我正在开发一个 React 应用程序,使用 Jest 和测试库进行我的测试。 I'd like to test what happens when the user clicks the browser's back button.我想测试当用户单击浏览器的后退按钮时会发生什么。 Is that possible, and if so, how?这可能吗,如果可以,怎么做? I know I could use Cypress but I'd prefer to avoid adding that to my project.我知道我可以使用 Cypress,但我宁愿避免将其添加到我的项目中。

If you're using React Router, first you need access to the history object in your test and then you can call history.goBack() .如果您使用的是 React Router,首先您需要访问测试中的 history 对象,然后您可以调用history.goBack()

There are a few options to get the history object:有几个选项可以获取历史对象:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 jest、react、testing-library 为这个组件编写单元测试? - How can I write a unit test using jest, react, testing-library for this component? 如何在 jest 和 @testing-library/react 中测试 catch 部分 - How to test catch part in jest and @testing-library/react 如何使用@testing-library/user-event 版本 14 在 React 中测试 `onKeyDown` 道具? - How can I test `onKeyDown` prop in React with @testing-library/user-event version 14? 使用 testing-library 和 jest 的 React 组件抛出的测试错误 - Testing error thrown by a React component using testing-library and jest 我如何断言哪个值已传递给<li>与 jest 和 testing-library/react 反应的关键属性 - How can I assert which value has been passed to a <li> key attribute in react with jest and testing-library/react 如何测试我的操作、状态和 UI。 我正在使用带有 jest 和 testing-library 的上下文 API? - How do I test my actions, state and UI. I'm using context API with jest and testing-library? 我将如何使用 Jest 和 React 测试库对此进行测试? - How would I test this using Jest & React Testing library? 如何使用 React、Jest 和 React-testing-library 为带有令牌的 api 调用编写单元测试? - How can I write unit test for api call with token using React, Jest and React-testing-library? 如何使用@testing-library/react 和 react-test-renderer 测试由 Redux 状态控制的输入值? - how to test input value controlled by Redux state using @testing-library/react and react-test-renderer? 如何使用jest和react-testing-library测试上下文提供的功能? - How can I test functions that are provided by context using jest and react-testing-library?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM