Created
August 9, 2018 03:34
-
-
Save jkyoutsey/32db32bdbcdd96e49cdb7a6f1fa32272 to your computer and use it in GitHub Desktop.
Angular CanDeactivate Guard Unit Tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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