【问题标题】:Testing fork() in Redux Saga with Jest在 Redux Saga 中使用 Jest 测试 fork()
【发布时间】:2019-04-10 01:59:01
【问题描述】:

目前我一直在尝试为我的 redux 传奇“getExchanges”创建一些单元测试,但是在浏览了一些文档和站点后,我发现在这方面运行单元测试的信息并不多。

以下是我正在尝试测试的传奇故事以及围绕它的任何代码。目标是测试 saga 是否正常运行,并确保 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(用 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')

我对一个笑话测试用例的尝试

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

【问题讨论】:

  • return the test 是什么意思?

标签: reactjs redux jestjs redux-saga


【解决方案1】:

我推荐redux-saga-test-plan

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

【讨论】:

    猜你喜欢
    • 2018-06-10
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多