user9353955
user9353955

Reputation:

Angular - Router unit testing with testing module and RouterMock

I've read several questions about how to unit test routing. But nothing fits my case really. I have a navbar-comp. with several [routerLink]=[...] And when I simulate a click event. I want for instance to call expect(router.navigate).toHaveBeenCalledWith(*path*);

But I am already failing on the test setup: It throws me everytime a: cannot find root of undefined.

Test suite

describe('NavbarComponent', () => {
  let component: NavbarComponent;
  let fixture: ComponentFixture<NavbarComponent>;

  const router: Router = jasmine.createSpyObj('Router', ['navigate']);

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        NgbModule.forRoot(),
        RouterTestingModule
      ],
      providers: [
        {provide: Router, useValue: router}
      ],
      declarations: [
        NavbarComponent,
      ]
    })
      .compileComponents();
  }));

  it('should navigate on click - home', () => {
    (<jasmine.Spy>router.navigate).and.stub();
    const debugElm = fixture.debugElement.nativeElement.querySelector('#navLogo');
    debugElm.click();

    expect(router.navigate).toHaveBeenCalledWith(['/stories']);
  });

When I delete the RoutingTestingModule import then it throws me: Cannot bind to routerLink - which I actually need to test. Really frustrating... Does anyone has a solution for this?

Upvotes: 0

Views: 3351

Answers (1)

Ayala
Ayala

Reputation: 1164

The RouterTestingModule already provides a mock Router instance so there is no need to provide one explicitly in the test. Try something like that:

describe('NavbarComponent', () => {
  let component: NavbarComponent;
  let fixture: ComponentFixture<NavbarComponent>;
  let navigateSpy: Spy;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        NgbModule.forRoot(),
        RouterTestingModule
      ],
      declarations: [
        NavbarComponent,
      ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(NavbarComponent);
    component = fixture.componentInstance;
    navigateSpy = spyOn(TestBed.get(Router), 'navigate'); // <= init spy 
  });

  it('should navigate on click - home', () => {
    const debugElm = fixture.debugElement.nativeElement.querySelector('#navLogo');
    debugElm.click();

    expect(navigateSpy).toHaveBeenCalledWith(['/stories']); // <= check spy
  });

Upvotes: 4

Related Questions