How to test Angular2's router.navigate?

前端 未结 4 1003
囚心锁ツ
囚心锁ツ 2021-01-31 07:58

I\'ve run into missing messages in other unit tests, but just to have a nice isolated example, I created an AuthGuard that checks if a user is

相关标签:
4条回答
  • 2021-01-31 08:44

    If you want to test the router without mocking it you can just inject it into your test and then spy directly on the navigate method there. The .and.stub() will make it so the call doesn't do anything.

    describe('something that navigates', () => {
        it('should navigate', inject([Router], (router: Router) => {
          spyOn(router, 'navigate').and.stub();
          expect(authGuardService.canActivate(<any>{}, <any>{})).toBe(false);
          expect(router.navigate).toHaveBeenCalledWith(['/login']);
        }));
      });
    
    0 讨论(0)
  • 2021-01-31 08:47

    I could mock the router and make my own navigate function, but then what's the point of RouterTestingModule? Perhaps you even want to check that navigation worked.

    There's no real point. If his is just a unit test for the auth guard, then just mock and spy on the mock to check that it's navigate method was called with the login argument

    let router = {
      navigate: jasmine.createSpy('navigate')
    }
    
    { provide: Router, useValue: router }
    
    expect(authGuardService.canActivate(<any>{}, <any>{})).toBe(false);
    expect(router.navigate).toHaveBeenCalledWith(['/login']);
    

    This is how unit tests should normally be written. To try to test any actual real navigation, that would probably fall under the umbrella of end-to-end testing.

    0 讨论(0)
  • 2021-01-31 08:59
         it(`editTemplate() should navigate to template build module with query params`, inject(
            [Router],
            (router: Router) => {
              let id = 25;
              spyOn(router, "navigate").and.stub();
              router.navigate(["/template-builder"], {
                queryParams: { templateId: id }
              });
              expect(router.navigate).toHaveBeenCalledWith(["/template-builder"], {
                queryParams: { templateId: id }
              });
            }
          ));
    
    0 讨论(0)
  • 2021-01-31 09:03

    this worked for me

    describe('navigateExample', () => {
        it('navigate Example', () => {
            const routerstub: Router = TestBed.get(Router);
            spyOn(routerstub, 'navigate');
            component.navigateExample();
        });
    });
    
    0 讨论(0)
提交回复
热议问题