How do I Mock RouterStateSnapshot for a Router Guard Jasmine test

后端 未结 4 1068
生来不讨喜
生来不讨喜 2021-02-05 05:23

I have a simple router guard and I am trying to test the canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ). I can create the ActivatedRouteSn

4条回答
  •  孤城傲影
    2021-02-05 05:57

    I needed to get the data in the route to test for user roles in my guard, so I mocked it this way:

    class MockActivatedRouteSnapshot {
        private _data: any;
        get data(){
           return this._data;
        }
    }
    
    describe('Auth Guard', () => {
       let guard: AuthGuard;
       let route: ActivatedRouteSnapshot;
    
       beforeEach(() => {
          TestBed.configureTestingModule({
             providers: [AuthGuard, {
                provide: ActivatedRouteSnapshot,
                useClass: MockActivatedRouteSnapshot
            }]
          });
          guard = TestBed.get(AuthGuard);
      });
    
      it('should return false if the user is not admin', () => {
         const expected = cold('(a|)', {a: false});
    
         route = TestBed.get(ActivatedRouteSnapshot);
         spyOnProperty(route, 'data', 'get').and.returnValue({roles: ['admin']});
    
         expect(guard.canActivate(route)).toBeObservable(expected);
      });
    });
    

提交回复
热议问题