diff --git a/src/app/guards/navigation-blocked/navigation-blocked.guard.spec.ts b/src/app/guards/navigation-blocked/navigation-blocked.guard.spec.ts new file mode 100644 index 00000000..18f99894 --- /dev/null +++ b/src/app/guards/navigation-blocked/navigation-blocked.guard.spec.ts @@ -0,0 +1,71 @@ +import { Component } from '@angular/core'; +import { TestBed, async, ComponentFixture, inject } from '@angular/core/testing'; +import { Observable } from 'rxjs'; +import { AlertController } from '@ionic/angular'; + +import { NavigationBlockedGuard, HasNavigationBlocked } from './navigation-blocked.guard'; + +@Component({ + template: '
' +}) +class HasNavigationBlockedMockComponent implements HasNavigationBlocked { + hasNavigationBlockedValue: Observable | Promise | boolean; + + hasNavigationBlocked(): Observable | Promise | boolean { + return this.hasNavigationBlockedValue; + } +} + +describe('NavigationBlockedGuard', () => { + let component: HasNavigationBlockedMockComponent; + let fixture: ComponentFixture; + let guard: NavigationBlockedGuard; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [], + declarations: [ HasNavigationBlockedMockComponent ], + schemas: [], + providers: [], + }) + .compileComponents(); + + guard = TestBed.inject(NavigationBlockedGuard); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(HasNavigationBlockedMockComponent); + + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(guard).toBeTruthy(); + }); + + it('should block navigation', (done) => { + + component.hasNavigationBlockedValue = true; + + guard.canDeactivate(component, {} as any, {} as any) + .then((canDeactivate) => { + expect(canDeactivate).toBeFalsy(); + done(); + }) + .catch(done); + }); + + it('should unblock navigation', (done) => { + + component.hasNavigationBlockedValue = false; + + guard.canDeactivate(component, {} as any, {} as any) + .then((canDeactivate) => { + expect(canDeactivate).toBeTruthy(); + done(); + }) + .catch(done); + }); + +}); diff --git a/src/app/guards/navigation-blocked/navigation-blocked.guard.ts b/src/app/guards/navigation-blocked/navigation-blocked.guard.ts new file mode 100644 index 00000000..6b6a38c4 --- /dev/null +++ b/src/app/guards/navigation-blocked/navigation-blocked.guard.ts @@ -0,0 +1,22 @@ +import { Injectable } from '@angular/core'; +import { ActivatedRouteSnapshot, RouterStateSnapshot, CanDeactivate } from '@angular/router'; +import { Observable } from 'rxjs'; + +export interface HasNavigationBlocked { + hasNavigationBlocked: () => Observable | Promise | boolean; +} + +@Injectable({ + providedIn: 'root' +}) +export class NavigationBlockedGuard implements CanDeactivate { + constructor() {} + + async canDeactivate(component: HasNavigationBlocked, + route: ActivatedRouteSnapshot, + state: RouterStateSnapshot) { + + return !component.hasNavigationBlocked(); + } +} +