angular 2 testing w/router

耗尽温柔 提交于 2019-12-06 01:08:28

Let's say you have the following component:

@Component({
  selector: 'home-comp',
  template: `<button (click)="login()" class="loginbtn">Login</button>
  `
})
export class HomePageContentComponent {
  constructor(private auth: Auth, private router: Router) { }

  login() {
    this.router.navigateByUrl(`/dashboard`);
  }
}

In your test after replacing real Router with mocked version:

{ provide: Router, useClass: RouterStub }

Inside you case:

it('Should log in and navigate to dashboard', inject([Router],(router:Router)=>{

router will be instance of RouterStub.

then you spy on for navigateByUrl method to watching how many times it was called

const spy = spyOn(router, 'navigateByUrl');

so when you clicking on the .loginbtn button router.navigateByUrl is running (see above component) and spy incrementes calls with some information(for example, what was called the argument)

Finally in this line

const navArgs = spy.calls.first().args[0];

is expected that your router.navigateByUrl method was called at least once then is getting passed argument from the first call.

Here is working Live Example

Possible you went wrong somewhere and your router.navigateByUrl isn't executed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!