I have a simple router guard and I am trying to test the canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot )
. I can create the ActivatedRouteSn
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);
});
});