How do I Mock RouterStateSnapshot for a Router Guard Jasmine test

后端 未结 4 1180
生来不讨喜
生来不讨喜 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:41

    I managed to do it slightly differently but it should work for you :

    ...
    
    let mockSnapshot:any = jasmine.createSpyObj("RouterStateSnapshot", ['toString']);
    
    @Component({
      template: ''
    })
    class RoutingComponent { }
    
    @Component({
      template: ''
    })
    class DummyComponent { }
    
    describe('Testing guard', () => {
      beforeEach(() => TestBed.configureTestingModule({
        imports: [
          RouterTestingModule.withRoutes([
            {path: 'route1', component: DummyComponent},
            {path: 'route2', component: DummyComponent},
            ...
          ])
      ],
      declarations: [DummyComponent, RoutingComponent],
      providers: [
        GuardClass,
        {provide: RouterStateSnapshot, useValue: mockSnapshot}
      ]
    }).compileComponents());
    
      it('should not allow user to overcome the guard for whatever reasons', 
        inject([GuardClass], (guard:GuardClass) => {
          let fixture = TestBed.createComponent(RoutingComponent);
          expect(guard.canActivate(new ActivatedRouteSnapshot(), mockSnapshot)).toBe(false);
      })
     ...
    

提交回复
热议问题