Reputation: 703
So I'm testing with Jasmine/Karma and am using Angular 4. I'm trying to test a function that looks like this:
As you can see, this.name assignment is not getting touched. I've tried testing with:
it('should make sure name is set', () => {
component.retrievePageInfo();
expect(component.name).toBeDefined();
});
but it's undefined at this time. I'm not sure how to wait for it to finish. I've also tried:
it('should make sure name is set', () => {
component.retrievePageInfo().subscribe(art => {
expect(component.name).toBe(art["name"]);
});
});
But I get the error "Property 'subscribe' does not exist on type 'void'." But if I change the function to:
retrievePageInfo() {
return this.httpClient.get("/api/art/" + this.art_id)
.subscribe(art => {
this.name = art['name'];
});
}
I get the error "Property 'subscribe' does not exist on type 'Subscription'." but I need the subscribe here.
Help, please!
Edit: A rough example would be nice because I just can't seem to get this right. I'm currently trying to split this into a function that returns an observable and another that uses it, but my tests still aren't catching it
Edit: Here's my newest attempt: I've imported fakeAsync and tick
it('should set name value', fakeAsync(() => {
expect(component.name).toBeUndefined();
spyOn(component, "retrievePageInfo");
component.retrievePageInfo();
tick();
fixture.detectChanges();
expect(component.name).toBeDefined();
}));
Yet I still get a failure of "Expected undefined to be defined."
Upvotes: 3
Views: 1700
Reputation: 56946
You need to look at async unit testing:
it('#getObservableValue should return value from observable',
(done: DoneFn) => {
service.getObservableValue().subscribe(value => {
expect(value).toBe('observable value');
done();
});
});
The code above is from the docs: https://angular.io/guide/testing#service-tests
Upvotes: 1