如何正确测试redux异步操作(错误:操作必须是普通对象。将自定义中间件用于异步操作。)

时间:2018-08-17 10:39:43

标签: reactjs redux axios redux-thunk moxios

我正在尝试测试redux异步操作,该操作会从JSON文件返回一堆模拟数据。但是我遇到以下错误:

  

动作必须是普通对象。使用自定义中间件进行异步   动作。

 /**
 * fetch reports CSV data based on given report component name.
 * @memberof Actions
 * @param {String} fields the report component name
 * @returns {Array} Current component CSV data
 */
export async function fetchCSVData(fields, dispatch) {
    return new Promise(resolve => {
        const API_URL = `${cfg.serverURL}/graphs/${fields}`;
        var config = {
            headers: {
                'Content-type': 'application/json',
                'Access-Control-Allow-Origin': '*',
                Authorization: authHeader()
            }
        };

        return axios
            .get(API_URL, config)
            .then(response => {
                if (response.status === 200) {
                    return resolve(response.data);
                }
            })
            .catch(error => {
                if (error.response.status === 401) {
                    localStorage.removeItem('TOKEN');
                    store.dispatch(push('/unauthorized'));
                } else {
                    console.log(error);
                    store.dispatch({
                        type: ACTION.ERROR_RESPONSE,
                        payload: 'An error has been occurred, please try again later'
                    });
                    store.dispatch({
                        type: ACTION.RESET_MESSAGES
                    });
                }
            });
    });
}

这是我的测试,我测试了401禁止的错误

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import moxios from 'moxios';
import { storageMock } from '../../helpers/mock_local_storage';
import { mockRevenuesCsvData } from '../../data/mockData';
import * as ACTION from '../../actions/actionTypes';
import * as services from '../../actions/index';
import { fetchCSVData } from '../../actions/index';
global.localStorage = storageMock();
const mockStore = configureMockStore([thunk]);
let store;

describe('Fetch the csv data', () => {
    beforeEach(() => {
        moxios.install();
        store = mockStore({});
        localStorage.setItem('TOKEN', '12345');
        const token = localStorage.getItem('TOKEN');

        expect(token).toEqual('12345');
    });

    afterEach(() => {
       moxios.uninstall();
    });

    it('can return 401 forbidden error', async () => {
      moxios.wait(() => {
        let request = moxios.requests.mostRecent();
        request.config.headers.Authorization = 'Bearer 123457890';
        request.respondWith({
            status: 401,
            response: {
                timestamp: '2018-08-14T10:28:46.744+0000',
                status: 401,
                error: 'Unauthorized',
                message: 'You are not authorized to access this resource.'
            }
        });
       });

       const expectedActions = [
          {
            type: '@@router/CALL_HISTORY_METHOD',
            payload: {
                args: ['/unauthorized'],
                method: 'push'
           }
        }
       ];


    spyOn(services, 'fetchCSVData').and.returnValue(
       Promise.resolve(mockRevenuesCsvData)
    );

    var expectedField = 'Revenues';
    expect(expectedField).toBe('Revenues');

    fetchCSVData(expectedField);
    const actions = store.getActions();
    //**I cannot access the store.getActions, Returns []**
    console.log('actions', actions);
  });
});

spyOn处于活动状态的情况下,我不再收到错误,但无法测试预期的操作。

如果我使用

return store.dispatch(fetchCSVData(expectedField)).then(() => {console.log(store.getActions())});

我得到:

  

动作必须是普通对象。使用自定义中间件进行异步   动作。

0 个答案:

没有答案