使用lambda链接测试异步操作

时间:2018-06-13 21:27:34

标签: redux jestjs redux-thunk

我正在学习如何对一个简单的动作创建器进行单元测试,如下所示,并希望找到测试它的最佳方法。我在编写测试时已经从redux文档中找到了一个例子,但想知道是否可以用lambda链来测试异步操作。

行动:

export const toggleSelect = (id, key) => dispatch => {
  return dispatch({
    type: TOGGLE_LIST_ITEM,
    payload: { id, key },
  });
};

测试(开玩笑)

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import * as actions from '../';
import * as types from '../types';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('list actions', () => {
  it('should create an action to unselect all list items', () => {
    const id = '123';
    const key = 'selectedProspects';
    const expectedAction = {
      type: types.UNSELECT_ALL_OF_TYPE,
      key,
    };

    const store = mockStore();

    return actions.toggleSelect(id, key).then(() => {
      expect(store.getActions()).toEqual(expectedAction);
    });
  });
});

有没有人知道测试这个的好方法?我不确定这是否有助于编写更多可测试的代码,或者我是否只是遗漏了某些内容。

1 个答案:

答案 0 :(得分:0)

你非常接近,你只需要使用派遣:

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('list actions', () => {
  it('should create an action to unselect all list items', () => {
    const id = '123';
    const key = 'selectedProspects';
    const expectedAction = {
      type: types.UNSELECT_ALL_OF_TYPE,
      key,
    };

    const store = mockStore();

    return store.dispatch(actions.toggleSelect(id, key)).then(() => {
      expect(store.getActions()).toEqual(expectedAction);
    });
  });
});

你的行动本身不需要是一个thunk。您可以轻松地将其写为动作创建者......即

export function toggleSelect(id, key) {
    return {
        type: TOGGLE_LIST_ITEM,
        payload: { id, key },
    };
}