Search code examples
angularunit-testingkarma-runnerngrxeffects

How to mock ngrx action in Angular component?


//component code on init function

this.rootStore.dispatch(new action1());

In the effects I have calling the 'action1Success'

I have pipe for action1Success and subscribe function in component

//component code

this.actionListener$.pipe( ofType(  MyactionTypes.action1Success)).subscribe((success: SuccessObj) => { });

Solution

  • you can use provideMockActions

    import { provideMockActions } from '@ngrx/effects/testing';
    ...
    describe('RouterHistoryEffects', () => {
      let actions: ReplaySubject<any>;
      let effects: YourEffects;
    
      beforeEach(() => {
       TestBed.configureTestingModule({
        providers: [
          provideMockActions(() => actions)
        ]
      });
     ....
    

    and your test should be something like this

    // dispatch your action
    
    (actions$ as ReplaySubject).next({ type: '[Users] Get Users' })
    
    // subscribe to the Effect stream
    effects.getUsers$.subscribe(action => {
     expect(action).toEqual({
      type: '[Users API] action1Success',
      users: [...],
    });
    });