2017-06-01 90 views
7

如何在響應路由器v4中測試組件? 我嘗試使用jest和酶對重定向進行單元測試時失敗。React Router v4重定向單元測試

我的組件:

const AppContainer = ({ location }) => 
    (isUserAuthenticated() 
    ? <AppWithData /> 
    : <Redirect 
     to={{ 
      pathname: "/login", 
      state: { from: location } 
     }} 
     />); 

我試圖對它進行測試:

function setup() { 
    const enzymeWrapper = mount(
    <MemoryRouter initialEntries={["/"]}> 
     <AppContainer /> 
    </MemoryRouter> 
); 

    return { 
    enzymeWrapper 
    }; 
} 

jest.mock("lib/authAPI",() => ({ 
    isUserAuthenticated: jest.fn(() => false) 
})); 

describe("AppContainer component",() => { 
    it("renders redirect",() => { 
    const { enzymeWrapper } = setup(); 

    expect(enzymeWrapper.find("<Redirect></Redirect>")).toBe(true); 
    }); 
}); 

回答

10

回答我的問題。 基本上我做了我的組件的淺層渲染,並驗證如果通過身份驗證是呈現重定向組件,否則應用程序之一。 下面的代碼:

function setup() { 
    const enzymeWrapper = shallow(<AuthenticatedApp />); 

    return { 
    enzymeWrapper 
    }; 
} 

describe("AuthenticatedApp component",() => { 
    it("renders Redirect when user NOT autheticated",() => { 
    authApi.isUserAuthenticated = jest.fn(() => false); 
    const { enzymeWrapper } = setup(); 

    expect(enzymeWrapper.find(Redirect)).toHaveLength(1); 
    }); 

    it("renders AppWithData when user autheticated",() => { 
    authApi.isUserAuthenticated = jest.fn(() => true); 
    const { enzymeWrapper } = setup(); 

    expect(enzymeWrapper.find(AppWithData)).toHaveLength(1); 
    }); 
}); 
0

這是我測試的小例子,實際的URL變化,而不是僅僅在頁面上存在Redirect組件:

RedirectApp.js

import React from "react"; 
import { Route, Switch, Redirect } from "react-router-dom"; 

const RedirectApp = props => { 
    return (
    <Switch> 
     <Redirect from="/all-courses" to="/courses" /> 
    </Switch> 
); 
}; 

export default RedirectApp; 

RedirectApp.test.js

import React from "react"; 
import { MemoryRouter, Route } from "react-router-dom"; 
import { mount } from "enzyme"; 
import RedirectApp from "./RedirectApp"; 

it("redirects /all-courses to /courses",() => { 
    const wrapper = mount(
    <MemoryRouter initialEntries={[`/all-courses`]}> 
     <Route component={RedirectApp} /> 
    </MemoryRouter> 
); 

    expect(wrapper.find(RedirectApp).props().location.pathname).toBe("/courses"); 
}); 

通過在Route中包裹RedirectApp,MemoryRouter注入RedirectApp中的react-router道具(matchlocationhistory)。

enzyme讓你抓住這些props()location道具包括重定向後pathname,所以重定向的位置可以匹配。

這種方法有點哈克,但測試的優點是,重定向要去正確的地方,不只是一個Redirect存在。

或者,您可以export default withRouter(RedirectApp)RedirectApp.js自動獲取react-router道具注入。