2017-03-08 38 views
0

我有一个中间件,等待ARTICLE_REQUEST操作,执行fetch并在完成提取时调度ARTICLE_SUCCESSARTICLE_FAILURE操作。像这样使用thunk减少测试异步中间件

import { articleApiUrl, articleApiKey } from '../../environment.json'; 
import { ARTICLE_REQUEST, ARTICLE_SUCCESS, ARTICLE_FAILURE } from '../actions/article'; 

export default store => next => action => { 

    // Prepare variables for fetch() 
    const articleApiListUrl = `${articleApiUrl}list`; 
    const headers = new Headers({ 'Content-Type': 'application/json', 'x-api-key': articleApiKey }); 
    const body = JSON.stringify({ ids: [action.articleId] }); 
    const method = 'POST'; 

    // Quit when action is not to be handled by this middleware 
    if (action.type !== ARTICLE_REQUEST) { 
     return next(action) 
    } 

    // Pass on current action 
    next(action); 

    // Call fetch, dispatch followup actions and return Promise 
    return fetch(articleApiListUrl, { headers, method, body }) 
     .then(response => response.json()); 
     .then(response => { 
      if (response.error) { 
       next({ type: ARTICLE_FAILURE, error: response.error }); 
      } else { 
       next({ type: ARTICLE_SUCCESS, article: response.articles[0] }); 
      } 
     }); 

} 

我真的很想知道如何测试这个异步代码。我想看看后续操作是否会正确调度,并且可能调用fetch调用时使用正确的URL和参数。谁能帮我吗?

PS:我使用thunk虽然我没有绝对的把握它的功能,因为我只是跟着另一个代码示例

回答

0

你可以嘲笑fetch()功能,像这样:

window.fetch = function() { 
    return Promise.resolve({ 
    json: function() { 
     return Prommise.resolve({ … your mock data object here … }) 
    } 
    }) 
} 

或者您缠绕在函数整个中间件像这样:

function middlewareCreator (fetch) { 
    return store => next => action => { … } 
} 

,然后创建与实际取方法作为parame中间件所以你可以交换它进行测试或生产。

+0

问题是不是垫片获取,我可以使用'nock',而是如何测试异样 – Lukas

+0

你使用什么测试框架? – philipp

+0

我用酶与笑话 – Lukas