Dan*_*Dan 3 testing jestjs react-router
问题:我的 App 组件负责根据路径渲染其他组件。所以为了测试它,我需要能够“设置”路径。例如,我希望看到 SignUp 组件在路径为/sign-up时呈现。
我所做的:我认为我可以使用 initialEntries 为 MemoryRouter 提供初始路径(不成功)然后我认为我可以在 MemoryRouter 内的测试中直接使用 Route/Redirect 来设置路径,但这不起作用任何一个。
规格:
我花了一段时间试图自己解决这个问题。简而言之,您不能<Router>在其中嵌套 a ,<MemoryRouter>因为它们都是路由器。
解决方案示例:
Routes.js -从中删除<BrowserRouter>,以便您可以测试您的代码。
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import SignUp from '../SignUp/SignUp'; //your signup component
import Home from '../Home/Home'; //some other component for an example
const MyRoutes = () => (
<Switch>
<Route path="/" component={Home} />
<Route path="/signup" component={SignUp} />
</Switch>
);
export default MyRoutes;
Run Code Online (Sandbox Code Playgroud)
index.js -在此处添加<BrowserRouter>,因为您需要将 a 包装<Switch>在 a 中<Router>。
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import Routes from './Components/Routes/Routes';
ReactDOM.render(
(
<BrowserRouter>
<Routes />
</BrowserRouter>
), document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)
测试/Routes.test.js -现在<MemoryRouter>在这里添加测试。
import React from 'react';
import ReactDOM from 'react-dom';
import { MemoryRouter } from 'react-router-dom';
import Routes from '../Components/Routes/Routes';
const TestRoute = props => (
<MemoryRouter initialEntries={props.initialEntries}>
<Routes {...props} />
</MemoryRouter>
);
it('at /signup it displays the signup page', () => {
const div = document.createElement('div');
ReactDOM.render(<TestRoute initialEntries={['/signup']} />, div); // render on the route "/signup"
const elem = div.getElementsByClassName('signup')[0];
expect(elem).not.toBe(undefined); // check an element exists with that class
if(elem !== undefined) {
expect(elem.innerHTML).toEqual('signup'); // check it has worked
}
});
Run Code Online (Sandbox Code Playgroud)
换句话说,您将路由/交换机与路由器分开,以便您能够对其进行测试,因为您不能嵌套两个路由器。
我遇到了类似的问题,我发现以下方法适用于测试其行为根据路线而变化的组件:
\n\n<MemoryRouter initialEntries={[\'/about\']}>\n <Navigation {...props} />\n</MemoryRouter>\nRun Code Online (Sandbox Code Playgroud)\n\n在此实例中,快照显示类.active名称已添加到导航中的“about”链接。
似乎不起作用的是在保存初始路由的组件/容器周围添加内存路由器。为了简单起见,我将基本路由页面简化为:
\n\n<Router>\n <div className="App">\n <Navigation app={this.props.app} />\n <Switch>\n <Route exact path="/" component={Home} />\n <Route exact path="/about" component={About} />\n <Route exact path="/login" render={() => <Login app={this.props.app} />} />\n <Route exact path="/signup" render={() => <Signup app={this.props.app} />} />\n <Route exact path="/account" render={() => <Account app={this.props.app} />} />\n <Route component={ErrorPage} />\n </Switch>\n </div>\n</Router>\nRun Code Online (Sandbox Code Playgroud)\n\nReact-router 团队在当前的测试文档中指出:
\n\n\n\n我们进行了大量测试,以确保路线在位置更改时有效,因此您可能不需要测试这些内容。
\n