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

牧云@^-^@ 提交于 2019-12-05 17:28:51

问题


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


回答1:


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);
    });
  });
});



回答2:


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);
    });
  });

It works well but the problem is when an error occur. In this case error is not reported to the test runner (to jest in my case). I need to add try catch block to get error:

   it('should call a notification service method info with a payload', () => {
        actions$ = cold('a', { a: new notificationAction.NotificationShowAction(payload) });
        effects.notificationShow$.subscribe(() => {
            try {
                expect(service.info).toHaveBeenCalledWith(payload); 
            } catch (error) {
                fail('notificationShow$: ' + error);
            }
        });
    });


来源:https://stackoverflow.com/questions/48318095/how-to-unit-test-this-effect-with-dispatch-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!