久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

如何對異步 Redux 操作進行單元測試以模擬 ajax 響

How to unit test async Redux actions to mock ajax response(如何對異步 Redux 操作進行單元測試以模擬 ajax 響應)
本文介紹了如何對異步 Redux 操作進行單元測試以模擬 ajax 響應的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

我正在創建一個中間件,用于使用異步操作發出 ajax 請求.中間件攔截原始動作,執行 ajax 請求,并將原始動作與來自 url 的響應一起重新dispatch.

I am creating a middleware for making ajax requests using async actions. The middleware intercepts original action, performs ajax request, and re-dispatches the original action along with the response from the url.

所以,我的組件只會dispatch這樣的動作

So, my Component would merely dispatch an action like this

onClick() {
    dispatch(ActionCreator.fetchUser());
}

其余部分將由中間件處理,如下所示這里.

Rest will be taken care by the middleware as shown here.

我的問題是,我應該為單元測試做什么?我應該模擬 onClick 本身嗎?或者我應該編寫一個模擬中間件并使用模擬響應轉發操作?

My question is, what should I do for unit testing? Should I mock the onClick itself? or I should write a mocked middleware and forward the actions with the mocked response?

我不確定我應該采用哪種方法.我嘗試了幾種方法,但我嘗試的所有方法都沒有任何意義.

I am not sure which approach should I take. I tried several stuff, but none of what I tried made sense to me.

任何指針?

推薦答案

注意:下面的回答有些過時了.

這里描述了一種更簡單的更新方法.
不過,您仍然可以使用其他方式.

Note: answer below is slightly outdated.

A much simpler updated approach is described here.
You can still do it the other way too, though.

我們現在有 一個關于測試異步操作創建者的部分 在官方文檔中.

We now have a section on testing async action creators in the official docs.

對于使用 Redux Thunk 或其他中間件的異步操作創建者,最好完全模擬用于測試的 Redux 存儲.您仍然可以將 applyMiddleware() 與模擬商店一起使用,如下所示.您還可以使用 nock 來模擬 HTTP 請求.

For async action creators using Redux Thunk or other middleware, it’s best to completely mock the Redux store for tests. You can still use applyMiddleware() with a mock store, as shown below. You can also use nock to mock the HTTP requests.

function fetchTodosRequest() {
  return {
    type: ADD_TODOS_REQUEST
  };
}

function fetchTodosSuccess(body) {
  return {
    type: ADD_TODOS_SUCCESS,
    body
  };
}

function fetchTodosFailure(ex) {
  return {
    type: ADD_TODOS_FAILURE,
    ex
  };
}

export function fetchTodos(data) {
  return dispatch => {
    dispatch(fetchTodosRequest());
    return fetch('http://example.com/todos')
      .then(res => res.json())
      .then(json => dispatch(addTodosSuccess(json.body)))
      .catch(ex => dispatch(addTodosFailure(ex)));
  };
}

可以像這樣測試:

import expect from 'expect';
import { applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import * as actions from '../../actions/counter';
import * as types from '../../constants/ActionTypes';
import nock from 'nock';

const middlewares = [thunk];

/**
 * Creates a mock of Redux store with middleware.
 */
function mockStore(getState, expectedActions, onLastAction) {
  if (!Array.isArray(expectedActions)) {
    throw new Error('expectedActions should be an array of expected actions.');
  }
  if (typeof onLastAction !== 'undefined' && typeof onLastAction !== 'function') {
    throw new Error('onLastAction should either be undefined or function.');
  }

  function mockStoreWithoutMiddleware() {
    return {
      getState() {
        return typeof getState === 'function' ?
          getState() :
          getState;
      },

      dispatch(action) {
        const expectedAction = expectedActions.shift();
        expect(action).toEqual(expectedAction);
        if (onLastAction && !expectedActions.length) {
          onLastAction();
        }
        return action;
      }
    }
  }

  const mockStoreWithMiddleware = applyMiddleware(
    ...middlewares
  )(mockStoreWithoutMiddleware);

  return mockStoreWithMiddleware();
}

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll();
  });

  it('creates FETCH_TODO_SUCCESS when fetching todos has been done', (done) => {
    nock('http://example.com/')
      .get('/todos')
      .reply(200, { todos: ['do something'] });

    const expectedActions = [
      { type: types.FETCH_TODO_REQUEST },
      { type: types.FETCH_TODO_SUCCESS, body: { todos: ['do something']  } }
    ]
    const store = mockStore({ todos: [] }, expectedActions, done);
    store.dispatch(actions.fetchTodos());
  });
});

這篇關于如何對異步 Redux 操作進行單元測試以模擬 ajax 響應的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How can I get my jasmine tests fixtures to load before the javascript considers the document to be quot;readyquot;?(在 javascript 認為文檔“準備好之前,如何讓我的 jasmine 測試裝置加載?) - IT屋-程序員軟件開發技術
What do jasmine runs and waitsFor actually do?(jasmine 運行和等待實際上是做什么的?)
How to provide mock files to change event of lt;input type=#39;file#39;gt; for unit testing(如何提供模擬文件來更改 lt;input type=filegt; 的事件用于單元測試)
How to unit test a chained method using Jasmine(如何使用 Jasmine 對鏈式方法進行單元測試)
How do I inject $rootScope into an AngularJS unit test?(如何將 $rootScope 注入 AngularJS 單元測試?)
Jasmine - How to spy on a function call within a function?(Jasmine - 如何監視函數中的函數調用?)
主站蜘蛛池模板: 亚洲高清在线播放 | 国产在线小视频 | 亚洲欧洲中文 | 好姑娘高清在线观看电影 | 宅男噜噜噜66一区二区 | 欧美区在线| 国产一级视频在线播放 | 亚洲毛片在线 | 男人久久天堂 | 精品一级毛片 | 午夜精品久久久久久久久久久久久 | 欧美成视频 | 中文字幕一区在线观看视频 | 一区二区三区久久久 | 亚洲色在线视频 | 欧美二三区 | 亚洲精品一区中文字幕乱码 | 一级做a爰片性色毛片 | 日本精品一区二区 | 日韩视频―中文字幕 | 精品久久久久一区二区国产 | 夜夜草视频 | www.狠狠干 | 久久久久久高潮国产精品视 | 久久伊人精品 | 国产精品日韩高清伦字幕搜索 | 成人免费淫片aa视频免费 | 一级毛片视频 | 国产毛片久久久久久久久春天 | 狠狠伊人 | 欧美在线国产精品 | 欧美二级 | 一区2区 | 久久大陆 | 久久亚洲国产 | 99re| 中文字幕在线观看视频一区 | 国产一区二区三区在线 | 99久久婷婷国产亚洲终合精品 | 在线观看一区 | 国产精品成人一区二区三区 |