react 路由重定向

React testing-library is very convenient to test React components rendering from props, fire events and check DOM elements. react-router uses a <Redirect> component to trigger a redirect, but how can we test that this component is called using testing-library?

React testing-library非常方便地测试从props,fire事件和检查DOM元素渲染的React组件。 react-router使用<Redirect>组件触发重定向,但是如何使用testing-library测试该组件是否被调用?

Let’s say we have a CreateBookForm component that creates a new book. It calls our API when the form is submitted.

假设我们有一个CreateBookForm组件可以创建一本新书。 提交表单后,它将调用我们的API。

// BookCreateForm.js
import React, { useState } from 'react';
import api from './api';function CreateBookForm() {const [title, setTitle] = useState('');async function handleSubmit(event) {event.preventDefault();await api.createBook({ title });}return (<form onSubmit={handleSubmit}><inputplaceholder="Book's title"value={title}onChange={(event) => setTitle(event.target.value)}/><button>Create book</button></form>);
}export default CreateBookForm;

It’s easy to test that our api is called when the form is submitted with testing-library:

使用test-library提交表单时,很容易测试是否调用了我们的api:

// BookCreateForm.test.js
import React from 'react';
import { render, act, fireEvent, waitFor } from '@testing-library/react';import BookCreateForm from './BookCreateForm';
import api from './api';jest.mock('./api');test('it calls api on form submit', async () => {api.createBook = jest.fn(() => Promise.resolve({ id: 1 }));const { getByPlaceholderText, getByText, findByDisplayValue } = render(<BookCreateForm />);await act(async () => {const input = getByPlaceholderText(/Book's title/);fireEvent.change(input, { target: { value: 'Yama Loka Terminus' }});await findByDisplayValue(/Yama Loka Terminus/);const button = getByText(/Create book/);fireEvent.click(button);});expect(api.createBook).toHaveBeenCalledWith({ title: 'Yama Loka Terminus' });
});

Now, let’s say we want our component to redirect to the new book page once it’s created.

现在,假设我们希望我们的组件在创建后重新定向到新书页面。

// BookCreateForm.js
import React, { useState } from 'react';
import { Redirect } from 'react-router-dom'import api from './api';function CreateBookForm() {const [title, setTitle] = useState('');const [createdId, setCreatedId] = useState(null);async function handleSubmit(event) {event.preventDefault();const { id } = await api.createBook({ title });setCreatedId(id);}return createdId ?<Redirect to={`/book/${createdId}`}/> :(<form onSubmit={handleSubmit}><inputplaceholder="Book's title"value={title}onChange={(event) => setTitle(event.target.value)}/><button>Create book</button></form>);
}export default CreateBookForm;

We’ll probably have a router wrapping our form and a BookPage component:

我们可能会有一个路由器来包装我们的表单和一个BookPage组件:

// App.js
function App() {return (<div className="App"><BrowserRouter><Route path="/book/create"><BookCreateForm /></Route><Route path="/book/:id"><BookPage /></Route></BrowserRouter></div>);
}

Now, our test runner will complain that we use `<Redirect>` outside of a router, so let’s wrap our component test into one.

现在,我们的测试跑步者会抱怨我们在路由器外部使用了<Redirect>,因此让我们将组件测试包装成一个。

// BookCreateForm.test.js
// …
import { BrowserRouter } from 'react-router-dom';
// …const { container, getByPlaceholderText, getByText, findByDisplayValue } = render(<BrowserRouter><BookCreateForm /></BrowserRouter>);
// …

Everything is working fine, but how can we ensure that our form component is redirecting to the new page after the api’s response?

一切工作正常,但如何确保api响应后表单组件重定向到新页面?

That’s a tricky question and I’ve been struggling with this. I’ve seen some complex solutions involving creating fake routers or mocking the react-router module. But there’s actually a pretty simple way to test this.

这是一个棘手的问题,我一直在为此苦苦挣扎。 我已经看到了一些复杂的解决方案,包括创建假路由器或模拟react-router模块。 但是实际上有一种非常简单的方法可以测试这一点。

If we try to snapshot our component after our API was called, we’ll notice that it renders an empty div.

如果在调用API之后尝试快照组件,则会注意到它呈现了一个空div。

expect(container).toMatchInlineSnapshot(`<div />`);

That’s because the redirection indeed happened, but there was no route to redirect to. From the testing-library renderer perspective, they are no routes defined, we just ask it to render and empty router containing the form.

那是因为确实发生了重定向,但是没有重定向到的路由。 从测试库渲染器的角度来看,它们没有定义路由,我们只是要求它渲染并清空包含表单的路由器。

To ensure that our user gets redirected to /book/1 (as the book's id returned by our API mock is 1), we can add a route for that specific url with a simple text as children.

为了确保我们的用户被重定向到/book/1 (因为我们的API模拟返回的书的ID为1 ),我们可以为该特定url添加一个路由,并以简单文本作为子级。

const { container, getByPlaceholderText, getByText, findByDisplayValue } = render(<BrowserRouter><BookCreateForm /><Route path="/book/1">Book page</Route></BrowserRouter>);

And test that the component rendered the text:

并测试该组件是否呈现了文本:

expect(container).toHaveTextContent(/Book page/);

Our final test :

我们的最终测试:

// BookCreateForm.test.js
import React from 'react';
import { render, act, fireEvent } from '@testing-library/react';
import { BrowserRouter, Route } from 'react-router-dom';import BookCreateForm from './BookCreateForm';
import api from './api';jest.mock('./api');test('it calls api on form submit', async () => {api.createBook = jest.fn(() => Promise.resolve({ id: 1 }));const { container, getByPlaceholderText, getByText, findByDisplayValue } = render(<BrowserRouter><BookCreateForm /><Route path="/book/1">Book page</Route></BrowserRouter>);await act(async () => {const input = getByPlaceholderText(/Book's title/);fireEvent.change(input, { target: { value: 'Yama Loka Terminus' }});await findByDisplayValue(/Yama Loka Terminus/);const button = getByText(/Create book/);fireEvent.click(button);});expect(api.createBook).toHaveBeenCalledWith({ title: 'Yama Loka Terminus' });expect(container).toHaveTextContent(/Book page/);
});

翻译自: https://medium.com/@iwazaru/how-to-test-react-router-redirection-with-testing-library-c67504ddeec8

react 路由重定向


http://www.taodudu.cc/news/show-4376664.html

相关文章:

  • Node中间件和路由器
  • 自动驾驶定位技术之争:融合定位才是出路
  • Java与PHP之争
  • c++镇国之争游戏(带存档,无bug)
  • python画五环图_对Python安装及绘制五环图的初步认识,初识,pythonpython,与
  • ker矩阵是什么意思_矩阵光学
  • J0ker的CISSP之路:复习-Access Control(4)
  • 2021高考成绩查询理综各科得分,2021高考一共几科 总分多少分
  • 江苏计算机学业水平测试多少分过关,江苏学业水平测试2021年考试时间:合格性考试30分能过吗?...
  • 新买的硬盘怎么装系统
  • 桌面计算机里没有桌面显示不出来怎么办,电脑桌面图标不显示怎么设置|恢复电脑桌面图标的方法...
  • WEB服务器概述
  • WEB服务器的基本介绍
  • 电路b-3—06刘晏辰
  • neon 指令 c语言,Neon指令集优化快速入门教程
  • kernel_neon_begin
  • NEON 常用函数及其执行结果
  • 生成器之Send方法--python
  • Socket中send()函数和rece()函数详解
  • 论文阅读——Automatic Testing and Improvement of Machine Translation
  • 安卓下快速搜索文件实现历程{NDK}
  • java 编辑PDF 文件,或者填充数据
  • 如何把pdf文件放到服务器,将生成的PDF文件存储在服务器上
  • 【学海】再看傅里叶变换和欧拉公式
  • 蒟蒻重返c++,学海拾贝(二)
  • 学海 拾贝
  • 人工智能在刷题学海战术中的作用
  • 学海挣扎记
  • 中科大计算机科学技术导师周,中国科技大学计算机科学与技术学院导师教师师资介绍简介-周学海...
  • 2009成渝微型计算机处于空白,学海园大联考 2020届高三信息卷(二)文综答案

react 路由重定向_如何测试与测试库的路由器重定向React相关推荐

  1. react 小程序转换_如何将AngularJS 1.x应用程序转换为React应用程序-一次转换一个组件。

    react 小程序转换 Angular and React are both great frameworks/libraries. Angular provides a defined struct ...

  2. 创建react应用程序_通过创建食谱应用程序来学习在React中使用API

    创建react应用程序 Learn how to use external APIs with React and React Router in a full tutorial from Hamza ...

  3. python重定向_在Python中使用urlopen()防止“隐藏”重定向

    我正在使用BeautifulSoup进行网页抓取,并且在使用urlopen时遇到特定类型网站的问题.网站上的每个商品都有其独特的页面,并且商品具有不同的格式(例如:500 mL,1L,2L等). 当我 ...

  4. 华为5720设置静态路由不通_【干货分享】交换机与路由器在环路中的处理机制了解一下!...

    点击蓝字关注我们 - 今天小盟带大家来讨论一下 交换机与路由器在环路中的处理机制 - 01 基础配置 1---如图配置路由器各接口地址,AR-2为PC-1的网关路由器 2---AR-1配置静态默认路由 ...

  5. react 组件构建_让我们用100行JavaScript构建一个React Chat Room组件

    react 组件构建 by Kevin Hsu 通过徐凯文 让我们用100行JavaScript构建一个React Chat Room组件 (Let's Build a React Chat Room ...

  6. react 路由配置以及封装

    react 路由配置以及封装 1.新建App.tsx文件 import React, { Component } from 'react' import IsRouter from './router ...

  7. react核心虚拟dom_使用虚拟时间测试基于时间的React堆核心流

    react核心虚拟dom Reactor Core实现了Reactive Streams规范,并处理了(可能无限的)数据流. 如果您感兴趣,请查看它提供的出色文档 . 在这里,我假设对Reactor ...

  8. react路由守卫+重定向_React + Apollo:如何在重新查询后进行重定向

    react路由守卫+重定向 by Jun Hyuk Kim 金俊赫 React + Apollo:如何在重新查询后进行重定向 (React + Apollo: How to Redirect afte ...

  9. 大学生计算机python_人人都能学计算机:计算机科学入门与Python编程_学堂在线章节测试答案...

    查看答案 人人都能学计算机:计算机科学入门与Python编程_学堂在线章节测试答案 单击图层调板下方的新图层按钮可以产生新图层.A:错B:对 在图示的薄壁杆件截面图形中,形心与弯曲中心重合的截面有() ...

最新文章

  1. CSS实战经验:灵活运行注释带来的益处(转载)
  2. Oracle数据库ORA-12516:“listener could not find available handler with matching protocol stack!“问题解决方法
  3. [渝粤教育] 长沙民政职业技术学院 高职公共英语(一) 参考 资料
  4. excel vba真正的动态数组实例-按需定义数组大小
  5. 蒙特卡罗方法—举例说明(C++、python)
  6. mysql设置用户永不过期_在Navicat Premium中管理MySQL用户 - 第2部分:创建新用户
  7. 软件测试有效性指标,软件测试用例评审有效性的44个衡量标准[1]
  8. 用python画玫瑰花
  9. 基础算法优化——Fast Modular Multiplication
  10. 微型计算机之哈佛架构是什么?
  11. DevExpress中实现给GridControl下的GridView表格修改指定行、列的背景颜色和获取选择行的信息
  12. IMS 注册流程最新
  13. 四元素基础理论及其应用
  14. 分享七天写好SCI初稿:
  15. 查找缺失的DLL工具Dependency Walker
  16. Windows Service 2012 IIS Microsoft excel Application
  17. Python库-uiautomator2(app自动化)
  18. (1)定义一个Circle类,包含一个double型的radius属性代表圆的半径,一个 findArea()方法返回圆的面积。 (2)定义一个类PassObject,在类中定义一个方法printA
  19. 做外贸怎么收款?2020最新外贸B2B收款结汇方法详解!
  20. hive案例——影评

热门文章

  1. Apollo(一)-基本介绍
  2. Opencv--waitKey()函数详解
  3. Latex中调整多行公式行距(间距)的方法
  4. Windform对sql数据库进行操作
  5. tm1650中文资料_TM1650+msp430单片机 调试及遇到问题的总结
  6. Ghost 博客 SSL 证书过期的解决办法
  7. 如何使用IOS自动化测试工具UIAutomation
  8. python 淘宝滑块验证_python selenium 淘宝滑块验证码 问题
  9. 深度学习 warmup 策略
  10. qq邮箱服务器发信怎么配置,WordPress网站实现使用QQ邮箱作为SMTP发信服务器配置教程...