预期redux saga单元测试,但收到深度平等错误

时间:2019-07-22 17:19:33

标签: reactjs redux redux-saga

在redux saga中对简单的api调用进行单元测试时得到此错误。

  

●我的功能›测试api调用

expect(received).toEqual(expected) // deep equality

- Expected
+ Received

  Object {
    "@@redux-saga/IO": true,
    "combinator": false,
    "payload": Object {
-     "args": Array [
-       Object {
-         "completed": false,
-         "id": 1,
-         "title": "delectus aut autem",
-         "userId": 1,
-       },
-     ],
+     "args": Array [],
      "context": null,
      "fn": [Function getData],
    },
    "type": "CALL",
  }

我有这样设置的api调用。

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

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

Redux-saga

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);
}

我应该如何正确地对此进行单元测试,我缺少什么吗?

我也在参考本教程

https://codeburst.io/how-i-test-redux-saga-fcc425cda018

redux-saga单元测试

import {
  put, fork, takeLatest, call,
} from 'redux-saga/effects';
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 { cloneableGenerator } from '@redux-saga/testing-utils';
import {getData} from './data';

const testData = {
  userId: 1, 
  id: 1, 
  title: "delectus aut autem", 
  completed: false
}

describe('My feature', () => {
  it('testing api call', () => {
    // const data = getData(api.json.getData);
    // console.log(data)
    const generator = cloneableGenerator(getData)(fetchDataSuccess)
    // console.log(generator)
    expect(generator.next().value).toEqual(call(api.json.getData, testData));
  })
})

1 个答案:

答案 0 :(得分:1)

在您的传奇故事中,您将这样做,而没有数据传递到getData中:

const data = yield call(api.json.getData);

假设没有数据传入是正确的,那么您的测试将需要更新以匹配,这意味着testData没有用。删除testData,然后将断言修改为:

expect(generator.next().value).toEqual(call(api.json.getData));