在组件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();
}));