2016-09-05 60 views
1

我有我的反應Redux的項目,我想實現測試,但試圖測試組件時遇到了問題以下組件測試組件做出反應用酶和摩卡

Users.js

export class Users extends Component { 
componentWillMount() { 
    const dispatch = this.context.store.dispatch; 
    dispatch({ type: UserActions.fetchUsers(dispatch)}); 
} 

render() { 
    const {users,isFetching} = this.props; 
    return (
     <div> 
      <CardHeader 
       title={this.props.route.header} 
       style={{backgroundColor:'#F6F6F6'}}/> 
      <UserListHeader/> 
      {isFetching ? <LinearProgress mode="indeterminate" /> : <UserList users={users}/>} 
     </div> 
    ) 
} 
} 

Users.propTypes = { 
    users: PropTypes.array, 
    actions: PropTypes.object.isRequired 
}; 

Users.contextTypes = { 
    store: React.PropTypes.object.isRequired 
}; 

function mapStateToProps(state) { 
    return { 
     users: state.users.users, 
     isFetching:state.users.isFetching 
    } 
} 

function mapDispatchToProps(dispatch) { 
    return { 
     actions: bindActionCreators(UserActions, dispatch) 
    } 
} 

export default connect(
    mapStateToProps, 
    mapDispatchToProps 
)(Users); 

,我想測試它像終極版網站上的例子,但我遇到了問題

UsersSpec.js

import {Users} from '/containers/users/Users' 
const middlewares = [ thunk ]; 
const mockStore = configureMockStore(middlewares); 

function usersSetup() { 
const props = { 
    users: expect.createSpy(), 
    isFetching:expect.createSpy() 
}; 

const enzymeWrapper = mount(<Users />,{context:{store:mockStore}}); 

return { 
    props, 
    enzymeWrapper 
} 
} 

describe('Users',() => { 
    it('should render self and subcomponents',() => { 
     const { enzymeWrapper } = usersSetup(); 
     exp(enzymeWrapper.find(UserListHeader)).to.have.length(1); 

    }) 

}) 

但我得到的錯誤'TypeError:dispatch不是函數'我應該嘲笑componentWillMount函數或如何測試這個組件。

我應該只是測試愚蠢的孩子組件?任何指導都會很棒。謝謝

回答

0

mount函數提供完整的dom渲染,因此您需要在您的測試設置中設置jsdom。你可以在這裏看到更多的信息:

Error: It looks like you called `mount()` without a global document being loaded

的另一件事是,你應該提供當你定義contextchildContextTypes屬性與mount這樣的:

mount(<Users />, { 
    context: { store: mockStore }, 
    childContextTypes: { store: PropTypes.object } 
    }); 

但是如果你正在寫您應該使用由酶提供的功能shallow功能的React組件的單元測試。它只是呈現一個深層次的組件,因此在創建包裝器組件時不需要創建jsdom並提供上下文參數。在測試中渲染意味着你實際上正在編寫一個集成測試。

const wrapper = shallow(<Users />); 
wrapper.find(UserListMenu).to.have.length(1); 
+0

嗨,感謝您的答案,我有jsdom文件設置問題是'dispatch不是一個函數',這源於我的componentWillMount函數。所以我得到這個錯誤淺或安裝。解決這個問題的最佳方法是什麼 – JKX

+0

哦,我明白了,你不應該在組件中使用dispatch。由於您將'actions'作爲道具傳遞給您的組件,因此您可以在'componentWillMount'函數中輕鬆調用'this.props.actions.fetchUsers'。如果你真的想在組件中使用dispatch,我想你應該在測試文件的'mount'函數調用中定義'childContextTypes'。 – kosker

+0

啊好吧,開始有意義, '導出函數fetchUsers(調度)派遣(fetchUsersRequest()); 返回fetchUsersApi() 。然後(功能(響應){調度(fetchUsersSuccess(response.data.results))}) .catch(功能(前){調度(fetchUsersFailure(前))}) }」 以上是我的動作,我如何解決傳遞調度問題,因爲如果我調用'this.props.actions.fetchUsers();'我得到'派遣不是一個函數' – JKX