Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jkyoutsey/32db32bdbcdd96e49cdb7a6f1fa32272 to your computer and use it in GitHub Desktop.
Save jkyoutsey/32db32bdbcdd96e49cdb7a6f1fa32272 to your computer and use it in GitHub Desktop.
Angular CanDeactivate Guard Unit Tests
it('can route if unguarded', () => {
// Mock GuardedComponent.isGuarded = false, which returns true from canActivate()
mockComponent.returnValue = true;
expect(service.canDeactivate(mockComponent)).toBeTruthy();
});
it('will route if guarded and user accepted the dialog', () => {
// Mock the behavior of the GuardedComponent:
const subject$ = new Subject<boolean>();
mockComponent.returnValue = subject$.asObservable();
const canDeactivate$ = <Observable<boolean>>service.canDeactivate(mockComponent);
canDeactivate$.subscribe((deactivate) => {
// This is the real test!
expect(deactivate).toBeTruthy();
});
// emulate the accept()
subject$.next(true);
});
it('will not route if guarded and user rejected the dialog', () => {
// Mock the behavior of the GuardedComponent:
const subject$ = new Subject<boolean>();
mockComponent.returnValue = subject$.asObservable();
const canDeactivate$ = <Observable<boolean>>service.canDeactivate(mockComponent);
canDeactivate$.subscribe((deactivate) => {
// This is the real test!
expect(deactivate).toBeFalsy();
});
// emulate the reject()
subject$.next(false);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment