click dispatchEvent doesn't triggers the angular 6 directive while unit testing in Jasmine/Karma












0















This is my directive. It is directive for the rich text which is used in the html file in the [innerHtml] field.



import { Directive, ElementRef } from '@angular/core';
import { Router } from '@angular/router';

@Directive({
selector: '[appRichTextLink]'
})

export class RichTextLinkDirective {
rawHTML: string;
checkRouter = false;
checkLink = false;
constructor(public elem: ElementRef, private router: Router) {
setTimeout(() => {
if (this.elem.nativeElement.querySelectorAll) {
const routerLinks: any = this.elem.nativeElement.querySelectorAll("[href]");
const ref = this;
if (routerLinks.length > 0) {
for (let i = 0; i < routerLinks.length; i++) {
routerLinks[i].addEventListener('click', function(e) {
const hrefValue: string = this.getAttribute('href').toString();
if (hrefValue !== "" && hrefValue !== "#" && hrefValue.indexOf('http://') === -1
&& hrefValue.indexOf('https://') === -1 && hrefValue.indexOf('//') === -1) {
e.preventDefault();
ref.router.navigate([hrefValue]);
} else {
window.open(hrefValue);
e.preventDefault();
this.checkLink = true;
}
});
}
}
}
}, 2000);
}
}
}


==============



This is my unit test. When the dispatch event triggers the url changes and the test breaks giving the error - "VM435 main.js:946 GET http://localhost:9876/test 404 (Not Found)". Please help



import { RichTextLinkDirective } from './rich-text-link.directive';
import { Component, DebugElement } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { fakeAsync, tick } from '@angular/core/testing';
import { AppComponent } from 'src/app/app.component';
import { routes } from '../../app-routing.module'
import { from } from 'rxjs';
import {Location} from '@angular/common';
import { Router } from '@angular/router';


@Component({
template: `<p appRichTextLink type="text" [innerHtml]="richText1"></p>`
})
class TestingComponent {
richText1 = "<!DOCTYPE html> THIS IS A TEST COMPONENT<a href="/test">test</a><a href="https://www.google.com">shop products</a>.";
}

describe('RichTextLinkDirective', () => {

let fixture: ComponentFixture<TestingComponent>;
let appFixture: ComponentFixture<AppComponent>;

let directive: RichTextLinkDirective;
let debugElement: DebugElement;

let router: Router;
let location: Location;
//let hrefElements: any;
beforeAll(() => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
});

beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes(routes)],
declarations: [TestingComponent, RichTextLinkDirective, AppComponent],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestingComponent);
appFixture = TestBed.createComponent(AppComponent);

debugElement = fixture.debugElement.query(By.directive(RichTextLinkDirective));
directive = debugElement.injector.get<RichTextLinkDirective>(RichTextLinkDirective);

router = TestBed.get(Router);
location = TestBed.get(Location);

fixture.detectChanges();
});

it('should create an instance', () => {
const directive1 = new RichTextLinkDirective(null, null);
expect(directive1).toBeTruthy();
});

it('should route to the desired link', fakeAsync(() => {
const event = new MouseEvent('click', { bubbles: true, cancelable: true });
tick(2000);
const spy = spyOn(TestBed.get(Router), 'navigate');
directive.elem.nativeElement.querySelectorAll("[href]")[0].dispatchEvent(event);
fixture.detectChanges();
expect(spy).toHaveBeenCalledWith(['/test']);
}));
});









share|improve this question



























    0















    This is my directive. It is directive for the rich text which is used in the html file in the [innerHtml] field.



    import { Directive, ElementRef } from '@angular/core';
    import { Router } from '@angular/router';

    @Directive({
    selector: '[appRichTextLink]'
    })

    export class RichTextLinkDirective {
    rawHTML: string;
    checkRouter = false;
    checkLink = false;
    constructor(public elem: ElementRef, private router: Router) {
    setTimeout(() => {
    if (this.elem.nativeElement.querySelectorAll) {
    const routerLinks: any = this.elem.nativeElement.querySelectorAll("[href]");
    const ref = this;
    if (routerLinks.length > 0) {
    for (let i = 0; i < routerLinks.length; i++) {
    routerLinks[i].addEventListener('click', function(e) {
    const hrefValue: string = this.getAttribute('href').toString();
    if (hrefValue !== "" && hrefValue !== "#" && hrefValue.indexOf('http://') === -1
    && hrefValue.indexOf('https://') === -1 && hrefValue.indexOf('//') === -1) {
    e.preventDefault();
    ref.router.navigate([hrefValue]);
    } else {
    window.open(hrefValue);
    e.preventDefault();
    this.checkLink = true;
    }
    });
    }
    }
    }
    }, 2000);
    }
    }
    }


    ==============



    This is my unit test. When the dispatch event triggers the url changes and the test breaks giving the error - "VM435 main.js:946 GET http://localhost:9876/test 404 (Not Found)". Please help



    import { RichTextLinkDirective } from './rich-text-link.directive';
    import { Component, DebugElement } from '@angular/core';
    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import { By } from '@angular/platform-browser'
    import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
    import { RouterTestingModule } from '@angular/router/testing';
    import { fakeAsync, tick } from '@angular/core/testing';
    import { AppComponent } from 'src/app/app.component';
    import { routes } from '../../app-routing.module'
    import { from } from 'rxjs';
    import {Location} from '@angular/common';
    import { Router } from '@angular/router';


    @Component({
    template: `<p appRichTextLink type="text" [innerHtml]="richText1"></p>`
    })
    class TestingComponent {
    richText1 = "<!DOCTYPE html> THIS IS A TEST COMPONENT<a href="/test">test</a><a href="https://www.google.com">shop products</a>.";
    }

    describe('RichTextLinkDirective', () => {

    let fixture: ComponentFixture<TestingComponent>;
    let appFixture: ComponentFixture<AppComponent>;

    let directive: RichTextLinkDirective;
    let debugElement: DebugElement;

    let router: Router;
    let location: Location;
    //let hrefElements: any;
    beforeAll(() => {
    TestBed.resetTestEnvironment();
    TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
    });

    beforeEach(async(() => {
    TestBed.configureTestingModule({
    imports: [RouterTestingModule.withRoutes(routes)],
    declarations: [TestingComponent, RichTextLinkDirective, AppComponent],
    })
    .compileComponents();
    }));
    beforeEach(() => {
    fixture = TestBed.createComponent(TestingComponent);
    appFixture = TestBed.createComponent(AppComponent);

    debugElement = fixture.debugElement.query(By.directive(RichTextLinkDirective));
    directive = debugElement.injector.get<RichTextLinkDirective>(RichTextLinkDirective);

    router = TestBed.get(Router);
    location = TestBed.get(Location);

    fixture.detectChanges();
    });

    it('should create an instance', () => {
    const directive1 = new RichTextLinkDirective(null, null);
    expect(directive1).toBeTruthy();
    });

    it('should route to the desired link', fakeAsync(() => {
    const event = new MouseEvent('click', { bubbles: true, cancelable: true });
    tick(2000);
    const spy = spyOn(TestBed.get(Router), 'navigate');
    directive.elem.nativeElement.querySelectorAll("[href]")[0].dispatchEvent(event);
    fixture.detectChanges();
    expect(spy).toHaveBeenCalledWith(['/test']);
    }));
    });









    share|improve this question

























      0












      0








      0








      This is my directive. It is directive for the rich text which is used in the html file in the [innerHtml] field.



      import { Directive, ElementRef } from '@angular/core';
      import { Router } from '@angular/router';

      @Directive({
      selector: '[appRichTextLink]'
      })

      export class RichTextLinkDirective {
      rawHTML: string;
      checkRouter = false;
      checkLink = false;
      constructor(public elem: ElementRef, private router: Router) {
      setTimeout(() => {
      if (this.elem.nativeElement.querySelectorAll) {
      const routerLinks: any = this.elem.nativeElement.querySelectorAll("[href]");
      const ref = this;
      if (routerLinks.length > 0) {
      for (let i = 0; i < routerLinks.length; i++) {
      routerLinks[i].addEventListener('click', function(e) {
      const hrefValue: string = this.getAttribute('href').toString();
      if (hrefValue !== "" && hrefValue !== "#" && hrefValue.indexOf('http://') === -1
      && hrefValue.indexOf('https://') === -1 && hrefValue.indexOf('//') === -1) {
      e.preventDefault();
      ref.router.navigate([hrefValue]);
      } else {
      window.open(hrefValue);
      e.preventDefault();
      this.checkLink = true;
      }
      });
      }
      }
      }
      }, 2000);
      }
      }
      }


      ==============



      This is my unit test. When the dispatch event triggers the url changes and the test breaks giving the error - "VM435 main.js:946 GET http://localhost:9876/test 404 (Not Found)". Please help



      import { RichTextLinkDirective } from './rich-text-link.directive';
      import { Component, DebugElement } from '@angular/core';
      import { async, ComponentFixture, TestBed } from '@angular/core/testing';
      import { By } from '@angular/platform-browser'
      import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
      import { RouterTestingModule } from '@angular/router/testing';
      import { fakeAsync, tick } from '@angular/core/testing';
      import { AppComponent } from 'src/app/app.component';
      import { routes } from '../../app-routing.module'
      import { from } from 'rxjs';
      import {Location} from '@angular/common';
      import { Router } from '@angular/router';


      @Component({
      template: `<p appRichTextLink type="text" [innerHtml]="richText1"></p>`
      })
      class TestingComponent {
      richText1 = "<!DOCTYPE html> THIS IS A TEST COMPONENT<a href="/test">test</a><a href="https://www.google.com">shop products</a>.";
      }

      describe('RichTextLinkDirective', () => {

      let fixture: ComponentFixture<TestingComponent>;
      let appFixture: ComponentFixture<AppComponent>;

      let directive: RichTextLinkDirective;
      let debugElement: DebugElement;

      let router: Router;
      let location: Location;
      //let hrefElements: any;
      beforeAll(() => {
      TestBed.resetTestEnvironment();
      TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
      });

      beforeEach(async(() => {
      TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes(routes)],
      declarations: [TestingComponent, RichTextLinkDirective, AppComponent],
      })
      .compileComponents();
      }));
      beforeEach(() => {
      fixture = TestBed.createComponent(TestingComponent);
      appFixture = TestBed.createComponent(AppComponent);

      debugElement = fixture.debugElement.query(By.directive(RichTextLinkDirective));
      directive = debugElement.injector.get<RichTextLinkDirective>(RichTextLinkDirective);

      router = TestBed.get(Router);
      location = TestBed.get(Location);

      fixture.detectChanges();
      });

      it('should create an instance', () => {
      const directive1 = new RichTextLinkDirective(null, null);
      expect(directive1).toBeTruthy();
      });

      it('should route to the desired link', fakeAsync(() => {
      const event = new MouseEvent('click', { bubbles: true, cancelable: true });
      tick(2000);
      const spy = spyOn(TestBed.get(Router), 'navigate');
      directive.elem.nativeElement.querySelectorAll("[href]")[0].dispatchEvent(event);
      fixture.detectChanges();
      expect(spy).toHaveBeenCalledWith(['/test']);
      }));
      });









      share|improve this question














      This is my directive. It is directive for the rich text which is used in the html file in the [innerHtml] field.



      import { Directive, ElementRef } from '@angular/core';
      import { Router } from '@angular/router';

      @Directive({
      selector: '[appRichTextLink]'
      })

      export class RichTextLinkDirective {
      rawHTML: string;
      checkRouter = false;
      checkLink = false;
      constructor(public elem: ElementRef, private router: Router) {
      setTimeout(() => {
      if (this.elem.nativeElement.querySelectorAll) {
      const routerLinks: any = this.elem.nativeElement.querySelectorAll("[href]");
      const ref = this;
      if (routerLinks.length > 0) {
      for (let i = 0; i < routerLinks.length; i++) {
      routerLinks[i].addEventListener('click', function(e) {
      const hrefValue: string = this.getAttribute('href').toString();
      if (hrefValue !== "" && hrefValue !== "#" && hrefValue.indexOf('http://') === -1
      && hrefValue.indexOf('https://') === -1 && hrefValue.indexOf('//') === -1) {
      e.preventDefault();
      ref.router.navigate([hrefValue]);
      } else {
      window.open(hrefValue);
      e.preventDefault();
      this.checkLink = true;
      }
      });
      }
      }
      }
      }, 2000);
      }
      }
      }


      ==============



      This is my unit test. When the dispatch event triggers the url changes and the test breaks giving the error - "VM435 main.js:946 GET http://localhost:9876/test 404 (Not Found)". Please help



      import { RichTextLinkDirective } from './rich-text-link.directive';
      import { Component, DebugElement } from '@angular/core';
      import { async, ComponentFixture, TestBed } from '@angular/core/testing';
      import { By } from '@angular/platform-browser'
      import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
      import { RouterTestingModule } from '@angular/router/testing';
      import { fakeAsync, tick } from '@angular/core/testing';
      import { AppComponent } from 'src/app/app.component';
      import { routes } from '../../app-routing.module'
      import { from } from 'rxjs';
      import {Location} from '@angular/common';
      import { Router } from '@angular/router';


      @Component({
      template: `<p appRichTextLink type="text" [innerHtml]="richText1"></p>`
      })
      class TestingComponent {
      richText1 = "<!DOCTYPE html> THIS IS A TEST COMPONENT<a href="/test">test</a><a href="https://www.google.com">shop products</a>.";
      }

      describe('RichTextLinkDirective', () => {

      let fixture: ComponentFixture<TestingComponent>;
      let appFixture: ComponentFixture<AppComponent>;

      let directive: RichTextLinkDirective;
      let debugElement: DebugElement;

      let router: Router;
      let location: Location;
      //let hrefElements: any;
      beforeAll(() => {
      TestBed.resetTestEnvironment();
      TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
      });

      beforeEach(async(() => {
      TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes(routes)],
      declarations: [TestingComponent, RichTextLinkDirective, AppComponent],
      })
      .compileComponents();
      }));
      beforeEach(() => {
      fixture = TestBed.createComponent(TestingComponent);
      appFixture = TestBed.createComponent(AppComponent);

      debugElement = fixture.debugElement.query(By.directive(RichTextLinkDirective));
      directive = debugElement.injector.get<RichTextLinkDirective>(RichTextLinkDirective);

      router = TestBed.get(Router);
      location = TestBed.get(Location);

      fixture.detectChanges();
      });

      it('should create an instance', () => {
      const directive1 = new RichTextLinkDirective(null, null);
      expect(directive1).toBeTruthy();
      });

      it('should route to the desired link', fakeAsync(() => {
      const event = new MouseEvent('click', { bubbles: true, cancelable: true });
      tick(2000);
      const spy = spyOn(TestBed.get(Router), 'navigate');
      directive.elem.nativeElement.querySelectorAll("[href]")[0].dispatchEvent(event);
      fixture.detectChanges();
      expect(spy).toHaveBeenCalledWith(['/test']);
      }));
      });






      typescript unit-testing jasmine karma-runner angular7






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '18 at 6:45









      ArchitArchit

      12




      12
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53425259%2fclick-dispatchevent-doesnt-triggers-the-angular-6-directive-while-unit-testing%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53425259%2fclick-dispatchevent-doesnt-triggers-the-angular-6-directive-while-unit-testing%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

          Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

          A Topological Invariant for $pi_3(U(n))$