Mocking router.events.subscribe() Angular2

前端 未结 6 1204
生来不讨喜
生来不讨喜 2020-12-30 00:03

In my app.component.ts I have the following ngOnInit function:

ngOnInit() {
    this.sub = this.router.events.subscribe(e => {
      if (e instanceof Navi         


        
6条回答
  •  旧巷少年郎
    2020-12-30 00:49

    The Angular Testing Documentation shows how to do this using a Jasmine spy:

    const routerSpy = jasmine.createSpyObj('Router', ['navigateByUrl']);
    const heroServiceSpy = jasmine.createSpyObj('HeroService', ['getHeroes']);
    
    TestBed.configureTestingModule({
      providers: [
        { provide: HeroService, useValue: heroServiceSpy },
        { provide: Router,      useValue: routerSpy }
      ]
    })
    

    ...

    it('should tell ROUTER to navigate when hero clicked', () => {
    
      heroClick(); // trigger click on first inner 
    // 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'); });

提交回复
热议问题