【问题标题】:Test async middleware in redux with thunk使用 thunk 在 redux 中测试异步中间件
【发布时间】:2017-07-28 19:47:49
【问题描述】:

我有一个中间件等待ARTICLE_REQUEST 操作,执行fetch 并在提取完成时分派ARTICLE_SUCCESSARTICLE_FAILURE 操作。像这样

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,虽然我不确定它的功能,因为我只是按照另一个代码示例进行操作

【问题讨论】:

    标签: unit-testing testing redux react-redux redux-thunk


    【解决方案1】:

    您可以像这样模拟fetch() 函数:

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

    或者您将整个中间件包装在一个函数中,如下所示:

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

    然后以实际的 fetch 方法作为参数创建中间件,以便您可以将其用于测试或生产。

    【讨论】:

    • 问题不在于shim fetch,我可以使用nock,而是如何异步测试
    • 我用酶开玩笑
    猜你喜欢
    • 2016-04-24
    • 2017-03-03
    • 1970-01-01
    • 2021-09-14
    • 2021-10-04
    • 2016-12-20
    • 2018-01-31
    • 2021-08-18
    • 2020-10-28
    相关资源
    最近更新 更多