【问题标题】:jasmine test on route.data.subscribe()route.data.subscribe() 上的茉莉花测试
【发布时间】:2018-09-17 13:47:08
【问题描述】:

我有一个包含以下 2 种方法的组件。

如何在 ngOnInit() 上测试 nameList() 方法是否为 haveBeenCalledWith(students)

constructor(route: ActivatedRoute, location: Location) { 
}

ngOnInit() {
    this.route.data
    subscribe((data: { students: Students }) => {
       const students: Students = data.students;
       this.nameList(students);
    });
}

nameList(students: Student) {
  .....
}

到目前为止我所拥有的:

describe('ngOnInit', () => {
    it('should extract data from route', () => {

      component = fixture.componentInstance;

      spyOn(component.route.data, 'subscribe').and.callFake((data: { students: Students }) => { } );
      component.ngOnInit();
      fixture.detectChanges();

      expect(component.nameList).toHaveBeenCalledWith(students);

    });
  });

【问题讨论】:

    标签: angular typescript unit-testing jasmine karma-jasmine


    【解决方案1】:

    我的问题的解决方案是我不应该在路线上进行间谍活动。

    我希望使用正确的数据调用方法 nameList(),

    所以应该直接监视 nameList()。

    spyOn(component, 'nameList');
    component.ngOnInit();
    
    expect(component.nameList).toHaveBeenCalledWith(mockData);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多