本文介绍了@ ngrx/effects:测试一个效果会返回empty()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用@ ngrx/effects 4.1.1.我有一个效果,返回的是一个空的可观察对象,如下所示:

I am using @ngrx/effects 4.1.1. I have an effect that returns an empty observable like this:

@Effect() showDialog$: Observable<Action> = this
.actions$
.ofType( ActionTypes.DIALOG_SHOW )
.map( ( action: DialogAction ) => action.payload )
.switchMap( payload => {
    this.dialogsService.showDialog( payload.className );
    return empty();
} );

我正在尝试按照这些指南编写单元测试可以测试效果是否产生可观察到的空白.我有这个:

I am trying to write a unit test following these guidelines that will test that the effect yields an empty observable. I have this:

describe( 'DialogEffects', () => {
    let effects: DialogEffects;
    let actions: Observable<any>;
    const mockDialogService = {
        showDialog: sinon.stub()
    };

    beforeEach( () => {
        TestBed.configureTestingModule( {
            providers: [
                DialogEffects, provideMockActions( () => actions ),
                {
                    provide: DialogsService,
                    useValue: mockDialogService
                }
            ]
        } );

        effects = TestBed.get( DialogEffects );
    } );

    describe( 'showDialog$', () => {
        it( 'should return an empty observable', () => {
            const dialogName = 'testDialog';
            const action = showDialog( dialogName );

            actions = hot( '--a-', { a: action } );
            const expected = cold( '|' );

            expect( effects.showDialog$ ).toBeObservable( expected );
        } );
    } );
} );

但是,因果报应(v1.7.1)抱怨:

However, Karma (v1.7.1) complains:

如何测试效果是否返回empty()?我尝试使用dispatch: false修改效果元数据,但这没有效果.

How do I test that the effect returns empty()? I have tried modifying the effect metadata using dispatch: false, but this has no effect.

想法?

推荐答案

问题是您正在将实际结果与cold('|')进行比较.

The problem is that you are comparing the actual result against cold('|').

cold('|')中的竖线字符表示可观察流的完成.但是,您的效果将无法完成. empty()可观察对象确实完成了,但是从switchMap返回empty()只是看到该可观察对象已合并到效果可观察对象的流中-它无法完成效果可观察对象.

The pipe character in cold('|') represents the completion of the observable stream. However, your effect will not complete. The empty() observable does complete, but returning empty() from switchMap just sees that observable merged into the effect observable's stream - it does not complete the effect observable.

相反,您应该将实际结果与cold('')进行比较-这是一个不发出任何值且未完成的可观察对象.

Instead, you should compare the actual result against cold('') - an observable that emits no values and does not complete.

这篇关于@ ngrx/effects:测试一个效果会返回empty()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 07:03