与 React Router 2 匹配的单元测试路由

Unit testing route matching with React Router 2

我正在尝试为 React 应用程序添加单元测试,并想测试 React Router (2.0.1) 提供的路由。我想测试我提供的特定路径是否与路由匹配。我正在使用 Mocha 和 expect 编写我的测试。

我查看了 React Router 存储库上的文档,但我能看到的唯一测试指南解释了如何测试 <Link /> 以及它是如何呈现的。

假设我有以下代码:

// import statements omitted for brevity

export const routes = (
    <Route path="/" component={App}>
        <IndexRoute component={Index} />
        <Route path="/foo">
            <IndexRoute component={FooIndex} />
            <Route path="add" component={FooAdd} />
            <Route path=":fooId" component={FooDetails} />
        </Route>
    </Route>
)

ReactDOM.render(
    <Router history={browserHistory}>{routes}</Router>,
    document.getElementById('app')
)

如何测试在 routes 变量中创建的路由是否匹配以下内容:

但不是这样的路线:

本质上,我想检查每个预期的 URL 格式是否都有匹配它的路由,并且意外的 URL 不匹配任何路由。

我对路由呈现的元素不感兴趣,所以不想将我的测试建立在检查是否呈现特定事物的基础上,只是找到匹配的路由,最好是某种方式检查它是否确实是预期的路线(我想检查组件的名称是什么?)

非常感谢任何帮助。

谢谢

我们在 matchRoutes 的测试中对此进行了测试:https://github.com/ReactTraining/react-router/blob/v3/modules/__tests__/matchRoutes-test.js

你可以遵循这个模式。如果您无法通过引用识别您的路由,您确实也可以对呈现的组件进行断言。

由于 matchRoutes 未导出,您需要使用 match 助手(否则用于服务器端呈现),并检查 renderProps.routesrenderProps.components.