vendredi 21 juin 2019

How to test my version of guard in angular application

I have issues with testing a guard. I new in it and i don't have idea how to do that. My version of guard always block from leaving page with window and it works good. Somebody can tell me what i need to change to test this functionality?

cab-deactivate.guard.ts

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';

import { ComponentCanDeactivate } from './component-can-deactivate';

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<ComponentCanDeactivate> {
  public canDeactivate(component: ComponentCanDeactivate): boolean {
    if (!component.canDeactivate()){
      if (confirm("You have unsaved changes! If you leave, your changes will be lost.")) {
        return true;
      } 
      return false;     
    }
    return true;
  }
}

can-deactivate.guard.spec.ts (not working)

import { MockComponent } from '@app/canvas/window/services/window.service.spec';

import { CanDeactivateGuard } from './can-deactivate.guard';

describe('[CanDeactivateGuard]', () => {
  describe('canActivate', () => {
    let canDeactivateGuard: CanDeactivateGuard;
    let testValue;
    let mockComponent;

    it('should return false', () => {
      canDeactivateGuard = new CanDeactivateGuard();

      mockComponent = new MockComponent()
      testValue = canDeactivateGuard.canDeactivate(mockComponent);

      expect(testValue).toEqual(false);
    });

    it('should return true', () => {
        canDeactivateGuard = new CanDeactivateGuard();

        mockComponent = new MockComponent()
        testValue = canDeactivateGuard.canDeactivate(mockComponent);

        expect(testValue).toEqual(true);
      });
  });
});

Aucun commentaire:

Enregistrer un commentaire