【问题标题】:How to write test case to call a method inside a "router navigation end subscribe"?如何编写测试用例来调用“路由器导航端订阅”中的方法?
【发布时间】:2019-09-25 15:31:55
【问题描述】:

我正在根据路由器事件创建一些面包屑。 我创建了一个带有 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-test


    【解决方案1】:

    你可以这样做:

    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,
        ...
      ]
    });
    

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 2020-11-03
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      相关资源
      最近更新 更多