用Jest测试Redux Saga中的fork()

问题描述 投票:0回答:1

目前我一直在尝试为我的redux saga“getExchanges”创建一些单元测试,但是在浏览了一些文档和网站后,我发现在这个区域运行单元测试没有很好的信息。

以下是我正在尝试测试的传奇以及围绕它的任何代码。目标是测试saga是否正常运行并确保API以应有的方式提取信息。

获得交换传奇

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

上面的yi​​eld fork中的'async'引用

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(使用action()包装getExchanges操作并使用createAsyncActionTypes包装GET_EXCHANGES)

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')

我对a的攻击是一个测试案例

    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使用模拟数据正确地提取信息

reactjs redux jestjs redux-saga
1个回答
0
投票

我推荐redux-saga-test-plan

它让你expect产生某些效果,它让你mock任何效果。

© www.soinside.com 2019 - 2024. All rights reserved.