如何编写测试用例以调用“路由器导航端订阅”内部的方法?

问题描述 投票:1回答:1

我正在根据路由器事件创建一些面包屑。我已经创建了一个带有NavigationEnd和模拟路由器的路由器测试台,但是无法正常工作。不了解如何在订阅中调用我的方法,以及如何编写测试用例以调用这些方法]

ngOnInit() {
this.router.events.pipe(filter(e instance of NavigationEnd)).subscribe( event => {
// calling this method 
this.callmethod();
// Initiating my breadcrumb method by passing the event
this.initiateBreadcrumb(event);
});
angular unit-testing karma-jasmine angular-testing
1个回答
0
投票

您可以这样操作:

it('routing should call callmethod', () => {
    let callMethodSpy = spyOn(component, "callmethod").and.callThrough();
    component.ngOnInit();

    let event = new NavigationEnd(42, '/some-route', '/');
    TestBed.get(Router).events.next(event);

    expect(callMethodSpy).toHaveBeenCalled();
  });

并且不要忘记将RouterTestingModule导入到您的TestBed中。

TestBed.configureTestingModule({
  imports: [
    RouterTestingModule,
    ...
  ]
});
© www.soinside.com 2019 - 2024. All rights reserved.