Testing Redux Thunk Action Creator



我有一个Redux Action Creator,它利用Redux-thunk来执行一些逻辑来确定要派往商店的内容。它不是基于承诺的,就像HTTP请求一样,所以我在正确测试它方面存在一些问题。不需要测试该值何时符合条件以及何时不符合条件。由于动作创建者没有返回承诺,因此我无法在测试中运行..)。测试类似的最佳方法是什么?

同样,我相信对 getRemoveFilemetrics()动作创造者的确可以很简单地测试,因为它实际上确实返回了诺言。但是,我该如何断言,如果该值为removefiles并符合条件,该调用将会调用呢?该如何写在测试中?

事先感谢,因为这让我一直坚持过去几天。

动作创造者

export const handleSelection = (value, cacheKey) => {
    return dispatch => {
        if (value === "removeFiles") {
            dispatch(getRemoveFileMetrics(cacheKey));
        }
        dispatch({ type: HANDLE_SELECTION, value });
    };
};
export const getRemoveFileMetrics = cacheKey => {
    return dispatch => {
        dispatch({ type: IS_FETCHING_DELETE_METRICS });
        return axios
            .get(`../GetRemoveFileMetrics`, { params: { cacheKey } })
            .then(response => {
                dispatch({ type: GET_REMOVE_FILE_METRICS, payload: response.data });
            })
            .catch(err => console.log(err));
    };
};

开玩笑

it("should dispatch HANDLE_SELECTION when selecting operation", () => {
    const store = mockStore({});
    const value = "switchVersion";
    const expectedAction = [{
        type: MOA.HANDLE_SELECTION,
        value,
    }]; // TypeError: Cannot read property 'then' of undefined
    return store.dispatch(MOA.handleSelection(value)).then(() => {
        const returnedActions = store.getActions();
        expect(returnedActions).toEqual(expectedAction);
    });
});

新编辑

因此,基于丹尼·德洛特(Danny Delott)回答诺言的回答,我对通过以下方式进行了通过的测试:

export const handleSelection = (value, cacheKey) => {
    return dispatch => {
        if (value === "removeFiles") {
            return dispatch(getRemoveFileMetrics(cacheKey));
        }
        return new Promise((resolve, reject) => {
            resolve(dispatch({ type: HANDLE_SELECTION, value }));   
        });
    };
};

是否有理由明确地不回报您的动作创建者的承诺?看起来getRemoveFileMetrics正在返回承诺,它只是在handleSelection ...

中吞下

最简单的解决方案就是返回承诺:

export const handleSelection = (value, cacheKey) => {
    return dispatch => {
        if (value === "removeFiles") {
            return dispatch(getRemoveFileMetrics(cacheKey));
        }
        dispatch({ type: HANDLE_SELECTION, value });
        return new Promise();
    };
};

否则,事件循环完成后,您需要做出断言。您可以用包裹在获得.then行为的承诺中的SettieMout进行。

it("should dispatch HANDLE_SELECTION when selecting operation", () => {
    const store = mockStore({});
    const value = "switchVersion";
    const expectedAction = [{
        type: MOA.HANDLE_SELECTION,
        value,
    }];
   store.dispatch(MOA.handleSelection(value));
   // flush outstanding async tasks
   return new Promise(resolve => {
     setTimeout(resolve, 0);
   })
   .then(() => {
      const returnedActions = store.getActions();
      expect(returnedActions).toEqual(expectedAction);
    });
});

相关内容

  • 没有找到相关文章

最新更新