要回答您的最后一个问题,推荐的方法是在您的测试中使用<MemoryRouter>< *your component here* ></MemoryRouter>。 Typescript 没有发现该组件会将所需的道具传递给您的组件,因此我认为它不是是一种类型安全的方法。
这适用于 React Router v4,不适用于以前的版本。
对于测试使用 HOC withRouter 包装的组件的类型安全方法,您可以从 react-router 和 history 包构建位置、历史记录和匹配项。
此示例使用酶和快照测试,但也可以轻松用于任何其他测试。
这避免了我需要使用 <MemoryRouter> 作为 typescript 无论如何都不喜欢的包装器。
// Other imports here
import { createMemoryHistory, createLocation } from 'history';
import { match } from 'react-router';
const history = createMemoryHistory();
const path = `/route/:id`;
const match: match<{ id: string }> = {
isExact: false,
path,
url: path.replace(':id', '1'),
params: { id: "1" }
};
const location = createLocation(match.url);
test('shallow render', () => {
const wrapper = shallow(
<MyComponent history={history}
location={location}
match={match} />
);
expect(wrapper).toMatchSnapshot();
});
注意不要用它来测试实现细节,它可能很诱人,但如果你想重构它会给你带来很多痛苦。
为此创建一个助手可能是使其可重用的最佳方法。
import { createLocation, createMemoryHistory } from 'history';
import { match as routerMatch } from 'react-router';
type MatchParameter<Params> = { [K in keyof Params]?: string };
export const routerTestProps = <Params extends MatchParameter<Params> = {}>
(path: string, params: Params, extendMatch: Partial<routerMatch<any>> = {}) => {
const match: routerMatch<Params> = Object.assign({}, {
isExact: false,
path,
url: generateUrl(path, params),
params
}, extendMatch);
const history = createMemoryHistory();
const location = createLocation(match.url);
return { history, location, match };
};
const generateUrl = <Params extends MatchParameter<Params>>
(path: string, params: Params): string => {
let tempPath = path;
for (const param in params) {
if (params.hasOwnProperty(param)) {
const value = params[param];
tempPath = tempPath.replace(
`:${param}`, value as NonNullable<typeof value>
);
}
}
return tempPath;
};
现在我们可以在测试中使用routerTestProps 函数
const { history, location, match } = routerTestProps('/route/:id', { id: '1' });