问题描述
示例代码:
import React,{ FC } from 'react';
import { mount,ReactWrapper } from 'enzyme';
import { createMemoryHistory } from 'history';
import { MemoryRouter,Router,Route,Switch,Link } from 'react-router-dom';
type TRoutes = {
[key: string]: {
title?: string;
path: string;
component: FC;
};
};
const routes: TRoutes = {
start: {
title: 'start page',path: `/`,component: () => null
},destination: {
path: `/destination`,component: () => null
}
};
const initialEntries = [routes.start.path];
const history = createMemoryHistory({
initialEntries
});
let wrapper: ReactWrapper;
describe('Router test',() => {
beforeAll(() => {
wrapper = mount(
<MemoryRouter initialEntries={initialEntries}>
<Router history={history}>
<Link to={routes.destination.path}>Go to destination</Link>
<button
type="button"
onClick={() => {
history.push(routes.destination.path);
}}
>
Go to route
</button>
<Switch>
<Route path={routes.start.path} exact component={routes.start.component} />
<Route path={routes.destination.path} exact component={routes.destination.component} />
</Switch>
</Router>
</MemoryRouter>
);
});
describe('Link',() => {
beforeAll(() => {
history.push(routes.start.path);
});
it(`should render Link - Go to destination`,() => {
expect(wrapper.find('a').at(0).exists).toBeTruthy();
});
it(`should update history from='${routes.start.path}' to location='${routes.destination.path}' on Link click`,() => {
wrapper
.find('a')
.at(0)
.simulate('click');
// wrapper.update();
expect(history.location.pathname).toEqual(routes.destination.path);
});
});
describe('button',() => {
beforeAll(() => {
history.push(routes.start.path);
});
it(`should render button - Go to destination`,() => {
expect(wrapper.find('button').at(0).exists).toBeTruthy();
});
it(`should update history from='${routes.start.path}' to location='${routes.destination.path}' on history.push`,() => {
wrapper
.find('button')
.at(0)
.simulate('click');
// wrapper.update();
expect(history.location.pathname).toEqual(routes.destination.path);
});
});
});
我上面有4个测试。
-
它应该测试链接是否存在=通过
-
点击链接应更新历史记录=失败
-
它应该测试按钮是否存在=通过
-
单击按钮应更新历史记录=通过
历史记录仅在我执行history.push时更新,而在单击链接时不会更新。
从-react-router-dom上的文档中可以看出,该方法有效并且应该起作用: https://reactrouter.com/web/guides/testing
the url bar),you can add a route that updates a variable in the test:// app.test.js
test("clicking filter links updates product query params",() => {
let history,location;
render(
<MemoryRouter initialEntries={["/my/initial/route"]}>
<App />
<Route
path="*"
render={({ history,location }) => {
history = history;
location = location;
return null;
}}
/>
</MemoryRouter>,node
);
act(() => {
// example: click a <Link> to /products?id=1234
});
// assert about url
expect(location.pathname).toBe("/products");
const searchParams = new URLSearchParams(location.search);
expect(searchParams.has("id")).toBe(true);
expect(searchParams.get("id")).toEqual("1234");
});
对此有何建议?
谢谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)