redux-saga“ all + takeEvery”单元测试

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

我是新来的反应。请帮助我进行redux-saga / effecs的单元测试。可以说我对单独的功能具有redux效果

export function* appEffects() {
    yield all([
        takeEvery(Types.CONFIGURE_LANGUAGE, configureLanguage),
        // other effects for this feature (removed to simplify example)
    ]);
}

function* configureLanguage(action: Actions.ConfigureLanguageAction) {
    const currentLanguage: string = 'en'; // simplified example
    yield put({ type: Types.SET_CURRENT_LANGUAGE, payload: currentLanguage });
}

我可以使用以下代码直接测试configureLanguage

import { runSaga } from 'redux-saga';


    async function recordSaga(saga: any, initialAction: any) {
        const dispatched: any = [];
        await runSaga(
            { dispatch: (action: any) => dispatched.push(action) },
            saga,
            initialAction
        ).toPromise;
        return dispatched;
    }

    it('should configure language', async () => {
        const action = appActions.service.configureLanguage('en');
        const dispatched = await recordSaga(
            configureLanguage
            action
        );
        expect(dispatched).toEqual([{ type: Types.SET_CURRENT_LANGUAGE, payload: 'en' }]);
    });

如何从configureLanguage测试appEffects?如果我尝试

const dispatched = await recordSaga(
            appEffects
            action
        );

我收到dispatched === []

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

[您没有调用toPromise方法返回诺言-现在,您正在await本身使用toPromise方法,因此recordSagarunSaga完成之前继续,因此dispatched仍为空当您到达expect时。

    async function recordSaga(saga: any, initialAction: any) {
        const dispatched: any = [];
        await runSaga(
            { dispatch: (action: any) => dispatched.push(action) },
            saga,
            initialAction
        ).toPromise(); // update here
        return dispatched;
    }
© www.soinside.com 2019 - 2024. All rights reserved.