2017-04-25 112 views
2

我是React/Redux的新手,已經在官方的redux文檔頁面上實現了一個基本示例。使用Jest測試外部Api調用(使用獲取函數)

需要一些幫助,我該如何測試以下功能,在普通的javascript函數調用外部API時,我的動作創建者是調用該函數的那個​​。

如何使用Jest測試API調用和我的動作創建器函數?

以下是存在的文件。

import fetch from 'isomorphic-fetch' 
 

 
export const REQUESTS_POSTS ='REQUESTS_POSTS'; 
 
export const RECEIVE_POSTS ='RECEIVE_POSTS'; 
 
export const SELECT_SUBREDDIT ='SELECT_SUBREDDIT'; 
 
export const INVALIDATE_SUBREDDIT ='INVALIDATE_SUBREDDIT'; 
 

 
export function selectSubreddit(subreddit) { 
 
    return{ 
 
     type:SELECT_SUBREDDIT, 
 
     subreddit 
 
    } 
 
} 
 

 
export function invalidateSubreddit(subreddit) { 
 
    return{ 
 
     type:INVALIDATE_SUBREDDIT, 
 
     subreddit 
 
    } 
 
} 
 

 
function requestsPosts(subreddit) { 
 
    return{ 
 
     type:REQUESTS_POSTS, 
 
     subreddit 
 
    } 
 
} 
 

 
function receivePosts(subreddit, json) { 
 
    return{ 
 
     type:RECEIVE_POSTS, 
 
     subreddit, 
 
     posts:json.data.children.map(child=>child.data), 
 
     receiveAt:Date.now() 
 
    } 
 
} 
 

 
function fetchPosts(subreddit) { 
 
    return dispatch=>{ 
 
     dispatch(requestsPosts(subreddit)); 
 
     return fetch(`https://www.reddit.com/r/${subreddit}.json`) 
 
      .then(response=>response.json()) 
 
      .then(json=>dispatch(receivePosts(subreddit,json))) 
 
    } 
 
} 
 

 
function shouldFetchPosts(state, subreddit) { 
 
    const posts = state.postsBySubreddit[subreddit]; 
 
    if(!posts){ 
 
     return true; 
 
    }else if(posts.isFetching){ 
 
     return false; 
 
    }else{ 
 
     return posts.didInvalidate 
 
    } 
 
    
 
} 
 

 
export function fetchPostsIfNeeded(subreddit) { 
 
    return (dispatch, getState) => { 
 
     if(shouldFetchPosts(getState(),subreddit)){ 
 
      return dispatch(fetchPosts(subreddit)) 
 
     } 
 
    } 
 
}

我已搜查上述的事情,但有不同的選項,如使用「諾克」圖書館等我上這也是檢驗其實際的正確的方式非常困惑。

回答