关于:
嘿,目前我正在尝试使用 jest 和 react 测试库为我的 react 组件编写测试。我也使用react-router。
问题:
我想检查当路径更改时应用程序是否路由到正确的组件而不与单个组件交互。
例如,如果当前路径名是“/impressum”,我只想从 Impressum 页面获取快照。
我不知道如何将路径传递到,<App>以便只显示一个 Route。
我正在尝试测试的组件:
import React from 'react'
import { BrowserRouter as Router, Switch, Route } from "react-router-dom"
import WeatherPage from "../WeatherPage/WeatherPage.js"
import AddWeatherPage from "../AddWeatherPage/AddWeatherPage.js"
import WeatherDetailsPage from "../WeatherDetailsPage/WeatherDetailsPage.js"
import DeleteWeatherPage from '../DeleteWeatherPage/DeleteWeatherPage.js'
import ImpressumPage from '../ImpressumPage/ImpressumPage.js'
class App extends React.Component {
render() {
return (
<Router>
<Switch>
<Route path="/weatherDetails" component={WeatherDetailsPage} />
<Route path="/addWeather" component={AddWeatherPage} />
<Route path="/deleteWeather" component={DeleteWeatherPage} />
<Route path="/impressum" component={ImpressumPage} />
<Route path="/" component={WeatherPage} />
</Switch>
</Router>
);
}
}
export default App
我试过的:
所以我已经尝试实现以下示例:https : //testing-library.com/docs/example-react-router
我还尝试
<App>使用<MemoryRouter>from -> import { MemoryRouter } from 'react-router'包装组件;并推送路线:https : //reacttraining.com/react-router/web/guides/testing我还尝试
<App>使用<Router>from -> import { Router } from "react-router-dom"包装组件;并推送历史对象。
我的基本测试代码
下面你可以看到我用于测试的代码,我在测试时做了一些更改,但这个基本部分一直保持不变。
describe("snapshot-test", () => {
it("renders component", () => {
const { asFragment } = render(
<App></App>
)
expect(asFragment()).toMatchSnapshot()
})
})