在OnInit中,我获取了一些数据的组件:
ngOnInit() {
this.userService.getUsers().subscribe(users => {
this.users= users.data;
});
}
在我的测试中,我存根这项服务:
const UserServiceStub = {
getUsers(): Observable<any> {
return of([{name: 'john doe'}, {name: 'jane doe'}]);
}
};
我定义了一个供应商:
providers: [ { provide: UserService, useValue: UserServiceStub } ],
现在我想测试呼叫已经作出,而数据元素上设置。
it('should be initialized with users', fakeAsync(() => {
const spy = spyOn(UserServiceStub, 'getUsers').and.callThrough();
}));
它看起来像我可以叫and.returnValue
,但我想要的数据来自于短线,我需要设置我的组件的Users
属性,以便我可以确认名单在我的模板进行更新。
我不能错过回调callThrough
和我没有找到有用的callthough().apply()
。
如何让我的存根执行?
你spy
对象可能是错的,你应该得到一个注入服务UserService
和spy
其方法的实例。
let userService: UserService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ { provide: UserService, useValue: UserServiceStub } ],
});
userService = TestBed.get(UserService);
});
it('should be initialized with users', fakeAsync(() => {
const spy = spyOn(userService , 'getUsers').and.callThrough();
}));