【问题标题】:Testing Async Redux Action Jest测试异步 Redux Action Jest
【发布时间】:2017-11-30 22:36:11
【问题描述】:

我无法从异步 redux 操作中获取正确的输出。我使用 Jest、redux-mock-adapter 和 thunk 作为工具。

根据 redux 关于测试异步 thunk 的文档 (https://redux.js.org/docs/recipes/WritingTests.html#async-action-creators),我的测试应该返回一个包含两个操作的数组。但是,我的测试只返回第一个动作,而不是应该在成功获取时返回的第二个动作。我想我只是在这里遗漏了一些小东西,但至少可以说很麻烦。

Redux 操作

export const getRemoveFileMetrics = cacheKey => 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 => err);
};

测试

it("getRemoveFileMetrics() should dispatch GET_REMOVE_FILE_METRICS on successful fetch", () => {
        const store = mockStore({});
        const cacheKey = "abc123doremi";
        const removeFileMetrics = {
            cacheKey,
            duplicateFileCount: 3,
            uniqueFileCount: 12,
        };
        const expectedActions = [
            {
                type: MOA.IS_FETCHING_DELETE_METRICS,
            },
            {
                type: MOA.GET_REMOVE_FILE_METRICS,
                payload: removeFileMetrics,
            }
        ];
        mockRequest.onGet(`/GetRemoveFileMetrics?cacheKey=${cacheKey}`).reply(200, removeFileMetrics);
        return store.dispatch(MOA.getRemoveFileMetrics(cacheKey)).then(() => {
            const returnedActions = store.getActions();
            expect(returnedActions).toEqual(expectedActions);
        });
    });

输出

Expected value to equal:
    [{ "type": "IS_FETCHING_DELETE_METRICS" }, { "payload": { "cacheKey": "abc123doremi", "duplicateFileCount": 3, "uniqueFileCount": 12 }, "type": "GET_REMOVE_FILE_METRICS" }]
Received:
    [{ "type": "IS_FETCHING_DELETE_METRICS" }]

【问题讨论】:

    标签: javascript unit-testing redux jestjs redux-mock-store


    【解决方案1】:

    我使用的是jest-fetch-mock,而不是axios。以下是为我工作的行动。作为第一步,您可以重构为 async await。对我来说,它只能这样工作。

    我现在正试图弄清楚如何测试副作用 (showErrorAlert(jsonResponse);)。如果我在测试文件顶部模拟 showErrorAlert 实现(在我的示例中注释掉),那么我会遇到和你一样的问题。由于某种原因,使用 fetch 的操作不会被触发。

    export const submitTeammateInvitation = (data) => {
      const config = {
        //.....
      };
    
      return async (dispatch) => {
        dispatch(submitTeammateInvitationRequest());
    
        try {
          const response = await fetch(inviteTeammateEndpoint, config);
          const jsonResponse = await response.json();
    
          if (!response.ok) {
            showErrorAlert(jsonResponse);
            dispatch(submitTeammateInvitationError(jsonResponse));
    
            throw new Error(response.statusText);
          }
    
          dispatch(submitTeammateInvitationSuccess());
        } catch (error) {
          if (process.env.NODE_ENV === 'development') {
            console.log('Request failed', error);
          }
        }
      };
    };
    

    测试

    import configureMockStore from 'redux-mock-store';
    import thunk from 'redux-thunk';
    
    // jest.mock('../../../../_helpers/alerts', ()=> ({ showAlertError: jest.fn() }));
    
    const middlewares = [thunk];
    const createMockStore = configureMockStore(middlewares);
    
    ......
    
    it('dispatches the correct actions on a failed fetch request', () => {
      fetch.mockResponse(
        JSON.stringify(error),
        { status: 500, statusText: 'Internal Server Error' }
      );
    
      const store = createMockStore({});
      const expectedActions = [
        {
          type: 'SUBMIT_TEAMMATE_INVITATION_REQUEST',
        },
        {
          type: 'SUBMIT_TEAMMATE_INVITATION_FAILURE',
          payload: { error }
        }
      ];
    
      return store.dispatch(submitTeammateInvitation(data))
        .then(() => {
          // expect(alerts.showAlertError).toBeCalled();
          expect(store.getActions()).toEqual(expectedActions);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2018-04-27
      • 2017-04-14
      • 2020-06-12
      • 2020-03-15
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-30
      相关资源
      最近更新 更多