NGXS: How to test if an action was dispatched?

前端 未结 3 2198
遇见更好的自我
遇见更好的自我 2021-02-14 06:57

How to unit test whether an action was dispatched?

For example, in a LogoutService, I have this simple method:

  logout(username: string) {
    store.dis         


        
3条回答
  •  一个人的身影
    2021-02-14 07:17

    Using Jasmine Spies

    I believe that in unit testing the actual implementation of all the related dependencies should be mocked and hence we should not be including any actual stores in here. Here we are providing a jasmine spy for Store and just checking whether certain actions are dispatched with correct parameters. This could also be used to provide stub data too.

    describe('LogoutService', () => {
      let storeSpy: jasmine.SpyObj;
    
      beforeEach(() => {
        storeSpy = jasmine.createSpyObj(['dispatch']);
    
        TestBed.configureTestingModule({
          providers: [LogoutService, { provide: Store, useValue: storeSpy }]
        });
      })
    
      it('should dispatch Logout and Reset actions', () => {
        storeSpy.dispatch.withArgs([
          jasmine.any(ResetStateAction), 
          jasmine.any(LogoutAction)])
         .and
         .callFake(([resetAction, logoutAction]) => {
           expect(resetAction.payload).toEqual({...something});
           expect(logoutAction.payload).toEqual({...somethingElse});
        });
    
        TestBed.inject(LogoutService).logout();
    });
    

提交回复
热议问题