我正拼命尝试对HashRouter路由进行单元测试,但无法理解。我设法获得了使用酶的解决方案,但被技术负责人强迫使用ReactTestingLibrary。
有人能帮我指出正确的方向吗?
应用组件
import React, { Component } from 'react';
import { HashRouter } from 'react-router-dom'
import { create } from 'jss';
import { StylesProvider, jssPreset } from '@material-ui/styles';
import './App.css';
import Routes from './Routes';
class App extends Component {
render() {
return (
<HashRouter>
<Routes />
</HashRouter>
);
}
}
export default App;
路由组件
import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import { withRouter } from 'react-router';
import NetworksList from './pages/NetworksList';
import DealsList from './pages/DealsList';
class Routes extends Component {
render() {
return (
<div>
<Route path="/networks" component={NetworksList} />
<Route path="/deals" component={DealsList} />
</div>
);
}
}
export default withRouter(Routes);
应用程序组件测试
import React from 'react';
import App from './App';
import { render } from '@testing-library/react';
import { createMemoryHistory } from 'history'
import { Router } from 'react-router-dom'
import Routes from './Routes';
beforeEach(() => {
jest.resetAllMocks();
});
it.only('should render networks list page at #/networks', () => {
const history = createMemoryHistory()
history.push('networks');
const { container, getByText } = render(
<Router history={history}>
<Routes />
</Router>
)
});
答案 0 :(得分:0)
想法是使用基于哈希的历史记录“ createHashHistory”,以测试基于哈希的路由器。我已经为该哈希路由器React Testing库导航示例整理了一个工作示例。 https://codesandbox.io/s/hashrouter-react-router-react-testing-library-njmj5
例如,您的App.jsx是:
import Routes from "./Routes";
import { HashRouter as Router } from "react-router-dom";
export default function App() {
return (
<div className="App">
<h1>HashRouter Testing</h1>
<Router>
<ul className="nav justify-content-center">
<li className="nav-item">
<a class="nav-link active" href="#">
CompOne
</a>
</li>
<li className="nav-item">
<a class="nav-link active" href="#/comp-two">
CompTwo
</a>
</li>
</ul>
<Routes />
</Router>
</div>
);
}
Routes.jsx是:
import { Route, Switch } from "react-router-dom";
const CompOne = () => <div>Component One</div>;
const CompTwo = () => <div>Component Two</div>;
export default function Routes(props) {
return (
<Switch>
<Route exact path="/">
<CompOne />
</Route>
<Route exact path="/comp-two">
<CompTwo />
</Route>
</Switch>
);
}
然后,这是测试基于哈希的导航的方法:
import React from "react";
import { render, wait, waitForElement } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import { createHashHistory } from "history";
import App from "./App";
describe("AppRouter component", () => {
afterEach(jest.resetAllMocks);
it("navigates correctly", async () => {
const history = createHashHistory({ initialEntries: ["/"] });
history.push("/comp-two");
const { container, getByText, debug } = render(<App />);
await waitForElement(() => getByText(/Component Two/i));
debug();
});
});
希望有帮助!