React-redux:如何编写集成测试

时间:2016-08-17 23:52:45

标签: unit-testing reactjs integration-testing redux

我正在使用Enzyme测试我的反应和还原部分。我已经阅读并发现为组件编写集成测试也是一种很好的做法。 所以,这很简单,因为我必须调用操作创建者并检查他们对商店的更新值,但我有一些异步操作会返回dispatch个操作。

login.actions.js

export function loginUser(credentials) {
  return dispatch => {
    dispatch(action.loginRequest());
    return axios({
      method: 'post',
      url: `${api}/login`,
      data: {
        email: _.trim(_.get(credentials, 'email')),
        password: _.get(credentials, 'password')
      }
    })
      .then(response => {
        const { data } = response;

        if (_.isEqual(_.get(response, 'status'), 200)) {
          dispatch(action.loginSuccess(data));
        }
      })
      .catch(err => {
        dispatch(action.loginError(err));
      });
  };
} 

login.actionCreators.js

export function loginRequest() {
  return {
    type: types.LOGIN_REQUEST
  };
}
export function loginSuccess(payload) {
  return {
    type: types.LOGIN_SUCCESS,
    payload
  };
}
export function loginError(payload) {
  let error;
  switch (_.get(payload, 'response.status')) {
    case 422: {
      error = 'Invalid Credentials';
      break;
    }
    case 401: {
      error = 'Invalid user';
      break;
    }
    case 403: {
      error = 'Account not confirmed';
      break;
    }
    default:
      error = 'Something went wrong';
  }
  return {
    type: types.LOGIN_ERROR,
    error
  };
}

因此,为了执行完整的集成测试,我还必须测试login.actions.js,但由于dispatch通常返回普通对象,在我的情况下,它们返回一个调度函数。我该如何测试它们?

1 个答案:

答案 0 :(得分:6)

测试异步操作很简单。

我正在使用moxios ans sinon。您基本上可以将其扩展到所有不同的情况,并以相同的模式进行测试

import moxios from 'moxios';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { spy } from 'sinon';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('async actions', () => {
  beforeEach(() => {
    moxios.install();
  });

  afterEach(() => {
    moxios.uninstall();
  });
  it(`should create action LOGIN_SUCCESS after successful login`, () => {
    moxios.wait(() => {
      const request = moxios.requests.mostRecent();
      request.respondWith({
        status: 200,
        response: { message: 'success', status: '200' },
      });
    });
    const expectedActions = [
      { type: types.LOGIN_REQUEST },
      { type: types.LOGIN_SUCCESS, data: { message: 'success', status: '200' } },
    ];
    const store = mockStore({ auth: {} });
    return store.dispatch(loginUser('abcd', '1234'))
    .then(() => {
      expect(store.getActions()).to.eql(expectedActions);
    });
  });
});
相关问题