Reputation: 4360
In a component OnInit I'm fetching some data:
ngOnInit() {
this.userService.getUsers().subscribe(users => {
this.users= users.data;
});
}
In my tests, I stub this service:
const UserServiceStub = {
getUsers(): Observable<any> {
return of([{name: 'john doe'}, {name: 'jane doe'}]);
}
};
I define a provider:
providers: [ { provide: UserService, useValue: UserServiceStub } ],
Now I want to test that the call has been made and that data has been set on an element.
it('should be initialized with users', fakeAsync(() => {
const spy = spyOn(UserServiceStub, 'getUsers').and.callThrough();
}));
It looks like I can call and.returnValue
but I want the data to come from the stub and I need to set the Users
property of my component so that I can verify a list in my template is updated.
I couldn't pass a callback to callThrough
and I didn't find callthough().apply()
useful.
How do I get my stub execute?
Upvotes: 0
Views: 46
Reputation: 29745
Your spy
object is probably wrong, you should get the instance of an injected service UserService
and spy
on its method.
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();
}));
Upvotes: 1