前言本文遵循如何测试React异步组件?[1],这次我会继续使用@testing-library/react[2]来测试我们的React应用,并简单说明如何测试路由系统。基础示例以下代码使用react-routerV6版本,V5使用Switch封装组件。通常我们的程序会写如下代码:首先我们有2个页面src/routes/home.jsx主页exportdefaultfunctionHome(){return(这是首页
);}src/routes/about.jsx关于页面导出默认函数Home(){return(这是关于页面
);然后用HashRouter或者BrowserRouter包裹起来,形成我们程序的主入口index.jsxsrc/index.jsx程序入口import{HashRouter,Routes,Route,Link}from"react-router-dom";从“./routes/home”导入主页;从“./routes/about”导入关于;constNoMatch=()=>NoFound
;functionApp(){return(首页关于
}/>}/>}/>);}exportdefaultApp;因为我们的页面足够简单,所以页面不会报错。如果页面变量比较复杂,页面下的某个组件报错,就会导致白屏。比如在about页面下添加一个error组件nowimportReactfrom"react";functionAboutContent(){thrownewError("Throwatesterror");}exportdefaultfunctionAbout(){return(这是关于页面
);}此时,页面会报错,但是如果我们不点击about页面,我们的程序还是可以正常运行的,所以我们需要测试一下路由对于测试方法,我们知道@testing-library/react运行在node环境中,但是浏览器中没有HashRouter或者BrowserRouter,所以需要一个MemoryRouter。这时候我们需要将原来的index.jsx拆分成app。jsxsrc/index.jsx条目从“react”导入React;从“react-dom”导入ReactDOM;从“./App”导入App;从“react-router-dom”导入{HashRouter};ReactDOM.render(,document.getElementById("root"));src/app.jsximport{HashRouter,Routes,Route,Link}from"react-router-dom";importHomefrom"./routes/home";importAboutfrom"./routes/about";constNoMatch=()=>NoFound
;functionApp(){return(主页关于
}/>}/>);}exportdefaultApp;此时我们可以添加单元测试"react";import{Router}from"react-router-dom";importAppfrom"./App";test("测试整个路由系统",()=>{render();expect(screen.getByText(/这是主页/i)).toBeInTheDocument();userEvent.click(screen.getByText(/about/i));expect(screen.getByText(/this关于page/i)).toBeInTheDocument();});MemoryRouter[3]有2个参数第一个参数initialEntries={["/users/mjackson"]}配置初始化路由第二个参数initialIndex默认为最后一个initialEntriesTest404页面中的值期待(screen.getByText(/不Found/i)).toBeInTheDocument()})通用测试当有多个页面时,我们可以添加一个公共组件来确保每个页面都没有错误import{useLocation}from"react-router-dom";exportconstLocationDisplay=({children})=>{constlocation=useLocation();返回(<>{location.pathname}
{children}>);};在页面显示url,通过遍历确保每个页面都能正确渲染letroutes=["/","/about"];routes.forEach((route)=>{test(`Ensure${route}url可以正确显示`,()=>{render(