如何使用chai测试redux-sagas生成器功能测试用例中的catch块?

时间:2016-10-06 11:44:10

标签: javascript redux chai redux-saga

export function* testGeneratorFunction() {
   try {
       yield put(showSuccess(success));
   } catch (error) {
       yield put(showError(error));
   }
}

在上面的函数中,我需要测试catch块。我必须测试是否调用了showError()函数。

2 个答案:

答案 0 :(得分:2)

您可能希望使用帮助程序库,例如redux-saga-testing

免责声明:我写了这个库来解决同样的问题

对于您的具体示例,使用Jest(但对Mocha也一样),您可以写:

import sagaHelper from 'redux-saga-testing';
import { call, put } from 'redux-saga/effects';
import { showSuccess, showError } from './my-actions';
import { api } from './my-api';

function* testGeneratorFunction() {
    try {
        const data = yield call(api);
        yield put(showSuccess(data));
    } catch (e) {
        yield put(showError(e.message));
    }   
}

describe('When testing a Saga that throws an error', () => {
    const it = sagaHelper(testGeneratorFunction());

    it('should have called the API first, which will throw an exception', result => {
        expect(result).toEqual(call(api));
        return new Error('Something went wrong');
    });

    it('and then trigger an error action with the error message', result => {
        expect(result).toEqual(put(showError('Something went wrong')));
    });
});

describe('When testing a Saga and it works fine', () => {
    const it = sagaHelper(testGeneratorFunction());

    it('should have called the API first, which will return some data', result => {
        expect(result).toEqual(call(api));
        return 'some data';
    });

    it('and then call the success action with the data returned by the API', result => {
        expect(result).toEqual(put(showSuccess('some data')));
    });
});

我稍微修改了你的例子,因为" put"永远不会抛出异常。

在现实生活中,对API或其他逻辑的调用更有可能引发异常。

您会在project's GitHub.

上找到许多其他示例(更复杂的示例)

答案 1 :(得分:2)

手册中Error Handling有一个不错的章节。简而言之,您可以使用.throw代替.next来触发您的传奇中的catch阻止:

assert.deepEqual(
  gen.throw({message: "error!").value, // <-- notice the throw instead of next
  put({ type: 'PRODUCTS_REQUEST_FAILED', error }),
  "fetchProducts should yield an Effect put({ type: 'PRODUCTS_REQUEST_FAILED', error })"
)

我不熟悉Chai语法,但是例如使用Jest的expect它将是:

expect(gen.throw({message: "server ded"}).value).toEqual(
  put({ type: 'PRODUCTS_REQUEST_FAILED', error })
)