【问题标题】:Testing redux-saga functions that have api calls测试具有 api 调用的 redux-saga 函数
【发布时间】:2019-07-22 16:04:15
【问题描述】:

这是一个简单的 api 调用。

api

import axios from 'axios';   
export default {
  json: {
    getData: () => axios.get('https://jsonplaceholder.typicode.com/todos').then(res => res.data.slice(0, 5)),
  },
};

这个 api 调用在 redux-saga 函数中使用。

Redux 传奇

import {
  put, fork, takeLatest, call,
} from 'redux-saga/effects';
import { GET_DATA_SAGA } from '../actions/types';
import api from '../api';
import { fetchDataSuccess, fetchDataError } from '../actions/dataActions';

export function* getData() {
  try {
    const data = yield call(api.json.getData);

    console.log(data);

    yield put(fetchDataSuccess(data));
  } catch (err) {
    yield put(fetchDataError(err));
  }
}

export function* watchData() {
  yield takeLatest(GET_DATA_SAGA, getData);
}

export default function* () {
  yield fork(watchData);
}

我将如何测试此功能。我看过一些指南,但我没有偶然发现不复杂的单元测试。

到目前为止,这是我的单元测试,这就是我已经走了多远。

redux-saga 单元测试

import {put, fork, takeLatest, call} from 'redux-saga/effects';
import axios from 'axios';
import { GET_DATA_SAGA } from '../actions/types';
import {expectSaga} from 'redux-saga-test-plan';
import { fetchDataSuccess, fetchDataError } from '../actions/dataActions';
import api from '../api';

import {getData} from './data';

it('testing api call', () => {

    return expectSaga(api.json.getData)
})

【问题讨论】:

    标签: reactjs redux redux-saga


    【解决方案1】:

    你可以像这样简单地做到这一点,如果你有任何参数可以传递给你的生成器函数。 要进入下一个声明,您只需继续写generator.next()。 可能对你来说下一个是fetchDataSuccess 的动作。

    import {put, fork, takeLatest, call} from 'redux-saga/effects';
    import axios from 'axios';
    import { GET_DATA_SAGA } from '../actions/types';
    import {expectSaga} from 'redux-saga-test-plan';
    import { fetchDataSuccess, fetchDataError } from '../actions/dataActions';
    import api from '../api';
    
    import {getData} from './data';
    
    describe('My feature', () => {
      it('testing api call', () => {
        const generator = getData();
        expect(generator.next()).to.equal(yourApiResponse);
      })
    })

    【讨论】:

    • console.log(generator) 给了我一个未定义的类型和数据。我应该像这样fetchDataSuccess(api.json.getData) 传递api调用吗?
    • 我更新了代码。生成器必须是您的生成器函数getData()
    猜你喜欢
    • 1970-01-01
    • 2021-11-21
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 2019-08-15
    相关资源
    最近更新 更多