测试存根服务
Testing a stubbed service
在组件 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();
}));
在组件 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();
}));