Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test this effect (with {dispatch: false})?

ngrx and unit testing beginner here. I have the following effect:

@Injectable()
export class NotificationEffects {
  @Effect({dispatch: false})
  notificationShow$ = this.actions$
    .ofType(notificationAction.NOTIFICATION_SHOW)
    .do((action: notificationAction.NotificationShowAction) => {
      this.notificationService.info(action.payload.config);
    });

  constructor(private actions$: Actions, private notificationService: NotificationService) {}
}

Specifically, I would like to test that the notificationService method info has been called. How would I do that?

I have followed these examples but not found a solution:

https://netbasal.com/unit-test-your-ngrx-effects-in-angular-1bf2142dd459 https://medium.com/@adrianfaciu/testing-ngrx-effects-3682cb5d760e https://github.com/ngrx/effects/blob/master/docs/testing.md

like image 744
camden_kid Avatar asked Jan 18 '18 09:01

camden_kid


2 Answers

So it's as simple as this:

describe('notificationShow$', () => {
  let effects: NotificationEffects;
  let service: any;
  let actions$: Observable<Action>;
  const payload = {test: 123};

  beforeEach( () => {
    TestBed.configureTestingModule( {
      providers: [
        NotificationEffects,
        provideMockActions( () => actions$ ),
        {
          provide: NotificationService,
          useValue: jasmine.createSpyObj('NotificationService', ['info'])
        }
      ]
    } );

    effects = TestBed.get(NotificationEffects);
    service = TestBed.get(NotificationService);
  });

  it('should call a notification service method info with a payload', () => {
    actions$ = cold('a', { a: new notificationAction.NotificationShowAction(payload) });
    effects.notificationShow$.subscribe(() => {
      expect(service.info).toHaveBeenCalledWith(payload);
    });
  });
});
like image 114
camden_kid Avatar answered Nov 08 '22 18:11

camden_kid


The easiest (and officially suggested) way is to do it like this:

    it('should navigate to the customers detail page', () => {
      actions$ = of({ type: '[Customers Page] Customer Selected', name: 'Bob' });

      // create a spy to verify the navigation will be called
      spyOn(router, 'navigateByUrl');

      // subscribe to execute the Effect
      effects.selectCustomer$.subscribe();

      // verify the navigation has been called
      expect(router.navigateByUrl).toHaveBeenCalledWith('customers/bob');
    });

Here is the source.

like image 34
Neurotransmitter Avatar answered Nov 08 '22 19:11

Neurotransmitter