Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing NgRx 6 Effects

I am trying to test a ngrx effects in Angular 6 project, I always get error:

Expected $[0].notification.kind = 'C' to equal 'N'.
Expected $[0].notification.hasValue = false to equal true.

I tried this post https://brianflove.com/2018-06-28/ngrx-testing-effects and the one in the ngrx doc. Is there any requirements to make test on effects with ngrx 6 ? The error is not meaningful enough for me. Maybe someone have a complete example about how to do ?

Here's my effect:

initData$: Observable<Action> = this.actions$.pipe(
    ofType(INIT_DATA_ACTION),
    switchMap((data: any) => {
        return this.store.pipe(select(getAppDataResolved)).take(1).switchMap((resolved: any) => {
            if (!resolved) {
                return this.dataService.getInitData(this.loginService.user.id).switchMap((response: any) => {
                    return Observable.from([
                        new ItemsInitDataAction(response.userItems),
                        new InitDataResolvedAction(),
                    ]);
                });
            } else {
                return Observable.from([
                    new InitDataResolvedAction(),
                ]);
            }
        });
    }),
);

and my karma test:

it('should be created', () => {
    expect(effects).toBeTruthy(); // got success
});

it('basic test', () => { // got error
    const action = new appAction.InitDataAction();
    const outcome = new appAction.InitDataResolvedAction();

    actions.stream = hot('a', { a: action });
    const expected = hot('a', { b: outcome });

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

});

Thanks in advance for helping ;-)

like image 387
Laurent B Avatar asked Jul 14 '26 11:07

Laurent B


1 Answers

I think you need to insert a mock for the Selector, the next line in the console should be describe something about missing selector data.

let store: Store<any>

class MockStore {
    select(){}
}

TestBed.configureTestingModule({
   providers: [
     {
       provide: Store,
       useClass: MockStore
     }
   ]
});
store = TestBed.get(Store);

And in test suite you can use Spy to give you any slice of store that you want:

spyOn(store, 'select').and.returnValue(of(initialState));
like image 91
Tabares Avatar answered Jul 22 '26 22:07

Tabares



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!