我下面有2种方法的组件。
如何在ngOnInit()上测试方法nameList()是否具有BeenCalledWith(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);
});
});
答案 0 :(得分:0)
我的问题的解决方案是我不应该监视路线。
我希望已使用正确的数据调用方法nameList()
因此应直接监视nameList()。
spyOn(component, 'nameList');
component.ngOnInit();
expect(component.nameList).toHaveBeenCalledWith(mockData);
答案 1 :(得分:-1)
不要监视订阅,而要监视路由器本身。
const dataMock: any = { students: [] };
component['route'] = jasmine.createSpyObj('ActivatedRoute', ['data'])
component['route'].data.and.returnValue(of(dataMock));
// OR
spyOn(component['route'], 'data').and.returnValue(of(dataMock));
const spy = spyOn(component, 'nameList');
component.ngOnInit();
expect(spy).toHaveBeenCalledWith(dataMock.students);