Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

274
Views
Angular,unit test a part of navigation method

I need to test part of a method in my app component, that does a forEach of events in the router. The Karma coverage says that i need to test some lines of this method i dont know how to achieve it. How can i mock router events?

enter image description here

App.component

ngOnInit(): void {
    // Google tag manager
    this.pushGTMDataLayerForEveryVisitedPage();  
}

pushGTMDataLayerForEveryVisitedPage() {
    // push GTM data layer for every visited page
    this.router.events.forEach(item => {
      if (item instanceof NavigationEnd) {
        const gtmTag = {
          event: 'page',
          pageName: item.url
        };

        this.gtmService.pushTag(gtmTag);
      }
    });
}

unit test

describe('AppComponent', () => {

  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let store: MockStore<ILoaderState>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        TranslateModule.forRoot(),
        GoogleTagManagerModule.forRoot({
          id: environment.GTM_ID
        })
      ],
      declarations: [
        AppComponent
      ],
      providers: [
        PrimeNGConfig,
        provideMockStore(),
        GoogleTagManagerService
      ]
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    store = TestBed.inject(MockStore);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('GTM Is called',() => {
    component.isProduction = true
    const googleManagerSpy = spyOn(component, 'pushGTMDataLayerForEveryVisitedPage').and.callThrough();

    component.ngOnInit()

    expect(googleManagerSpy).toHaveBeenCalledTimes(1);
  })

For now im only evaluating that the method is called, but i dont know how to test those specific lines

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!