我有一个组件,它包含扩展RouteComponentProps
的props,如下所示:
export interface RouteComponentProps<P> {
match: match<P>;
location: H.Location;
history: H.History;
staticContext?: any;
}
现在,当我在应用程序中使用组件时,我会将以下属性传递给它:
<MyComponent
match={this.props.match}
location={this.props.location}
history={this.props.history}
/>
prop 已经可用,因为它是在react路由器内部运行的。
现在,如果没有match
、location
和history
,我该如何测试这个组件呢?
我需要模拟它们吗?或者它应该以某种方式自动加载一些帮助函数吗?
4条答案
按热度按时间3gtaxfhh1#
为了回答你的最后一个问题,推荐的方法是在你的测试中使用
<MemoryRouter>< *your component here* ></MemoryRouter>
。Typescript没有发现这个组件会把所需的属性传递给你的组件,因此我认为它不是类型安全的方法。要使用类型安全的方法来测试用HOC
withRouter
Package 的组件,您可以从react-router
和history
包构建位置、历史记录和匹配。本例使用酶和快照测试,但也可以使用任何其他测试。
这避免了我需要使用
<MemoryRouter>
作为typescript无论如何都不喜欢的 Package 器。注意不要用它来测试实现细节,它可能很诱人,但如果您想重构,它会给您带来很多痛苦。
为此创建一个helper可能是使其可重用的最好方法。
现在我们可以在测试中使用
routerTestProps
函数型
xoshrz7s2#
一位名叫Timmy Huang的先生提供了一个解决方案,其中包括一个简单的模拟...
https://spectrum.chat/react/help/how-do-you-test-components-that-use-routecomponentprops~495fe95b-6925-4e7f-bfe8-65a737c5d24e?m=MTU4Mjk1MjQ4ODQ0MA==
我用Jest试过了,成功了。我的组件有这个签名...
我的基本测试,以确认组件负载,然后看起来像这样...
型
nbysray53#
我一直在寻找一个很好的解决方案。我希望我可以在mapStateToProps函数或类似的东西中做到这一点,但还没有能够做到这一点。
我能做的最好的事情就是模拟这个,并传递匹配、位置和历史。
然后在我的测试中,我做到了:
hxzsmxv24#
我使用了类似于another answer的解决方案;使用助手构建 prop 。)我的助手使用
path-to-regexp
的compile
:在测试中这样使用它:
其中
renderWithProviders
与redux文档中的建议相同:型
关于
history@5
中缺少的createLocation
,这个评论建议parsePath
可以用作替代品,但我没有研究它,因为我仍然在v4上。