2017-06-22 69 views
3

我的目標是測試我的陣營路由器Route出口在我的應用和測試,如果它加載正確的組件,頁面等測試陣營路由器玩笑和酶

我有一個routes.js文件看起來如:

import React from 'react'; 
import { Route, IndexRoute } from 'react-router'; 
import { App, Home, Create } from 'pages'; 

export default (
    <Route path="/" component="isAuthenticated(App)"> 
    <IndexRoute component={Home} /> 
    <Route path="create" component={Create} /> 
    {/* ... */} 
    </Route> 
); 

注:isAuthenticated(App)在別處定義,並略去。

而且從我讀過,並理解,我可以測試它是這樣:

import React from 'react'; 
import { shallow } from 'enzyme'; 
import { Route } from 'react-router'; 
import { App, Home } from 'pages'; 
import Routes from './routes'; 

describe('Routes',() => { 
    it('resolves the index route correctly',() => { 
    const wrapper = shallow(Routes); 
    const pathMap = wrapper.find(Route).reduce((pathMapp, route) => { 
     const routeProps = route.props(); 
     pathMapp[routeProps.path] = routeProps.component; 
     return pathMapp; 
    }, {}); 
    expect(pathMap['/']).toBe(Home); 
    }); 
}); 

然而,在運行這個測試結果:

Invariant Violation: <Route> elements are for router configuration only and should not be rendered 

我想我明白了問題可能是我使用Enzyme的shallow方法。我從this SO question採取了這個解決方案。我相信我明白它試圖通過wrapper來解析調用Route調用,將每個調入一個哈希表並使用它來確定正確的組件是否在表中它應該是,但這是行不通的。

我已經瀏覽了很多文檔,Q & A和博客文章試圖找到「正確的方式」來測試我的路線,但我不覺得我在任何地方。我在我的方法基礎?

陣營:15.4.2

陣營路由器:3.0.2

酶:2.7.1

節點:6.11.0

回答

3

不能直接呈現Routes,但一個使用內部路由的組件Router。你指出的答案有完整的解決方案。

您可能還需要將測試環境下的browserHistory更改爲使用不同的history,該節點適用於節點。舊v3文檔: https://github.com/ReactTraining/react-router/blob/v3/docs/guides/Histories.md

作爲一個方面說明,什麼是測試點Route,我認爲已經在庫本身進行了測試?也許你的測試應該關注你的路由組件:它們是否根據路由參數呈現他們應該做的?這些參數你可以很容易地在你的測試中嘲笑,因爲它們只是道具。

我告訴你這一點,因爲在我的經驗理解什麼測試是作爲學習如何測試一樣重要。希望它有助於:)