0

While writing angular unit test for routing, is it okay to navigate with real values or we should use fakeAsync for router navigations?

Option 1

it('navigate to "home" takes you to /home', fakeAsync(() => {
        router.navigate(['home']);
        tick();
        expect(location.path()).toBe('/home');
 }));

Option 2

it('navigate to "home" takes you to /home', () => {
        router.navigate(['home']).then(() => {
            expect(location.path()).toBe('/home');
        });
    });
Sh. Pavel
  • 1,584
  • 15
  • 28
JPS
  • 2,730
  • 5
  • 32
  • 54

1 Answers1

0

As a rule you test the component, not the router, and care only if the component navigates with the right address under the given conditions.

You can create a mockRouter/spyRouter by using jasmine like this.

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

And then you can provide it to the testing module.

TestBed.configureTestingModule({
  providers: [
    { provide: Router,useValue: routerSpy }
  ]
});

And you can have a test spec like this.(example taken from the angular official doc)

    it('should tell ROUTER to navigate when hero clicked', () => {

  heroClick(); // trigger click on first inner <div class="hero">

  // args passed to router.navigateByUrl() spy
  const spy = router.navigateByUrl as jasmine.Spy;
  const navArgs = spy.calls.first().args[0];

  // expecting to navigate to id of the component's first hero
  const id = comp.heroes[0].id;
  expect(navArgs).toBe('/heroes/' + id,
    'should nav to HeroDetail for first hero');
});

Read more aboute Routing component testing.

Anuradha Gunasekara
  • 6,553
  • 2
  • 27
  • 37