使用Jest在Redux Saga中测试fork()

时间:2019-04-10 01:59:01

标签: reactjs redux jestjs redux-saga

当前,我一直在尝试为我的redux传奇“ getExchanges”创建一些单元测试,但是在浏览了一些文档和站点之后,我发现在此区域没有关于运行单元测试的重要信息。 / p>

下面是我要测试的传奇以及围绕它的所有代码。目的是测试该传奇故事是否正常运行,并确保API以应有的方式提取信息。

获取交流传奇

export function* getExchanges(action) {
  const state: storeType = yield select()
  yield fork(async, action, API.getExchanges, { userId: state.auth.userId })
}

上面yield分支中的“异步”参考

import { put, call } from 'redux-saga/effects'

import { asyncAction } from './asyncAction'

export const delay = ms => new Promise(res => setTimeout(res, ms))

/**
 * @description: Reusable asynchronous action flow
 *
 * @param action  : redux action
 * @param apiFn   : api to call
 * @param payload : payload to send via api
 */
export function* async(action, apiFn, payload) {
  const async = asyncAction(action.type)
  try {
    const { response, data } = yield call(apiFn, payload)
    console.log(`[Saga-API_SUCCEED - ${action.type}, ${response}, ]: , ${data}`)
    yield put(async.success(data))
  } catch (err) {
    console.log(`[Saga-API_FAILED: - , ${action.type}, ]: , ${err}`)
    yield put(async.failure(err))
  }
}

getExchanges操作

export const getExchanges = () => action(actionTypes.GET_EXCHANGES.REQUEST, {})

GET_EXCHANGES操作类型

export const GET_EXCHANGES = createAsyncActionTypes('GET_EXCHANGES')

asyncAction(将getExchanges操作与action()包装在一起,并将GET_EXCHANGES与createAsyncActionTypes包装在一起)

export type ASYNC_ACTION_TYPE = {
  REQUEST: string
  SUCCESS: string
  FAILURE: string,
}

export const createAsyncActionTypes = (baseType: string): ASYNC_ACTION_TYPE => {
  return {
    REQUEST: `${baseType}`,
    SUCCESS: `${baseType}_SUCCESS`,
    FAILURE: `${baseType}_FAILURE`,
  }
}

export function action(type, payload = {}) {
  return { type, payload }
}

export function asyncAction(actionType: string) {
  const asyncActionType = createAsyncActionTypes(actionType)
  return {
    success: response => action(asyncActionType.SUCCESS, response),
    failure: err => action(asyncActionType.FAILURE, err),
  }
}

getExchanges API

 export const getExchanges = ({ userId }) => API.request(`/exchange/${userId}`, 'GET')

我在一个开玩笑的测试用例中受伤

    import configureMockStore from 'redux-mock-store'
    import { runSaga } from 'redux'
    import createSagaMiddleware from 'redux-saga'
    import { exchangesSaga, getExchanges ,getBalances, selectExchange } from '../src/sagas/exchanges.saga'
    import * as api from '../src/api/transaction'
    import * as actionTypes from '../src/action-types/exchanges.action-types'
    import { action } from '../src/sagas/asyncAction'

    const sagaMiddleware = createSagaMiddleware()
    const mockStore = configureMockStore([sagaMiddleware]);

    export async function recordSaga(saga, initialAction) {
        const dispatched = [];

        // Run's a given saga outside of the middleware
        await runSaga(
        {
            // dispatch fulfills put
            dispatch: (action) => dispatched.push(action)
        },
        saga,
        initialAction
        ).done;

        return dispatched;
    }

    describe.only("getExchanges saga", () => {
        api.getExchanges = jest.fn()
        beforeEach(() => {
            jest.resetAllMocks()
        })

        it('should get exchanges from API and call success action', async () => {
            const getUserExchanges = {exchange, exchange2};
            api.getExchanges.mockImplementation(() => getExchanges);

            const initialAction = action(actionTypes.GET_EXCHANGES.REQUEST)
            const dispatched = await recordSaga(
            getExchanges,
            initialAction
            );

            expect(api.getExchanges).toHaveBeenCalledWith(1);
            expect(dispatched).toContainEqual(action(actionTypes.GET_EXCHANGES.SUCCESS));
        });
    })

由于我的测试用例尚不完整,我目前还没有得到太多帮助,我对如何执行此操作有点迷茫。

我希望能够返回测试并确保API使用模拟数据正确提取信息

1 个答案:

答案 0 :(得分:0)

我推荐redux-saga-test-plan

它可以让您expect产生某些效果,并且可以mock产生任何效果。