如何单元测试异步Redux动作来模拟ajax响应

时间:2015-10-08 09:26:53

标签: javascript reactjs jasmine redux

我正在创建一个使用异步操作发出ajax请求的中间件。中间件拦截原始操作,执行ajax请求,并重新dispatch原始操作以及url的响应。

所以,我的Component只会dispatch这样的动作

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

中间件会照看休息,如here所示。

我的问题是,我应该怎么做单元测试?我应该嘲笑onClick本身吗?或者我应该编写一个模拟的中间件并用模拟的响应转发行为?

我不确定应采取哪种方法。我试过了several stuff,但我尝试过的一切对我都没有意义。

任何指针?

2 个答案:

答案 0 :(得分:25)

注意:下面的答案略显过时。

描述了一种更为简单的更新方法here 不过,你仍然可以用其他方式做到这一点。

我们现在在官方文档中有a section on testing async action creators

对于使用Redux Thunk或其他中间件的异步操作创建者,最好完全模拟Redux存储以进行测试。您仍然可以将applyMiddleware()与模拟商店一起使用,如下所示。您还可以使用nock模拟HTTP请求。

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());
  });
});

答案 1 :(得分:2)

事实证明,我不需要模拟任何商店方法或任何东西。它就像模拟ajax请求一样简单。我正在使用superagent,所以我做了类似这样的事情

const mockResponse = {
    body: {
        data: 'something'
    }
};

spyOn(superagent.Request.prototype, 'end').and.callFake((cb) => {
    cb(null, mockResponse); // callback with mocked response
});

// and expect it to be called
expect(superagent.Request.prototype.end).toHaveBeenCalled();