1

I'm having a hard time trying to mock Router in my Jest Unit Test.

I have a service breadcrumb.service.ts that takes Router as a dependency. It basically takes the URL from it and changes www.yoursite.com/section-one/page-one to ['home', 'section-one, 'page-one']

I can see two approaches - 1) mock the router or 2) create a new router and navigate it to the correct page?

import { fakeAsync, TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot, Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { BreadcrumbService } from './breadcrumb.service';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from "@angular/platform-browser-dynamic/testing";
import { routes } from '../../app-routing.module';




describe('BreadcrumbService', () => {
  let sut: BreadcrumbService;
  let router: Router;
  let route: ActivatedRouteSnapshot;


  TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
  
  beforeEach(() => {

    TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes(routes)],
      providers: [BreadcrumbService]
    });
    sut = TestBed.inject(BreadcrumbService);
  });

  beforeEach(() => {
    router = TestBed.get(Router)
    route = TestBed.get(ActivatedRouteSnapshot)
    sut = new BreadcrumbService(router);
  });



  it('should be created', () => {
    expect(sut).toBeTruthy();
  });


  // Test Breadcrumb Service
  it('should return 3 breadcrumbs', fakeAsync(() => {

    // Arrange
    router.navigateByUrl('/section-one/page-one')


    // Act
    let result = new BreadcrumbService(router);


    // Assert
    expect(result).toBe(['home', 'section-one', 'page-one'])

  }));

});

That's my attempt at the test so far. I can't seem to get it working. The error I keep hitting is:

zone-testing.js is needed for the fakeAsync() test helper but could not be found.
Please make sure that your environment includes zone.js/testing

I have googled that error and there's a lot of people saying to add

import 'zone.js';
import 'zone.js/testing';

to test.ts.

I don't have a src/test.ts file. I assume it's because I'm using Jest? So no idea where to add it? Adding it to the breadcrumb.service.spec.ts file does not work.

Long story short, how do I test my service that has a Router dependency? How do I mock the router, providing the URL to test the service with?

Scottish Smile
  • 455
  • 7
  • 22

0 Answers0