'Test Typescript Service : Multiple Subscription on one Observable
I am having a problem performing a test on a typescript service. I have a function that returns an observable. I use .subscribe() to look at the result and verify assertions. When I do a test with a single .subscribe() on this observable everything works fine. But when I add another call to .subscribe() to my test after changing some variables or not I get inconsistent results for my whole test. For example, the entire test is successful while some assertions are false Could you help me understand where the problem comes from please? I still have troubles with observables..
public myFunction(param1: string, param2: string): Observable<boolean> {
return this.apiService.apiName(param1, param2)
.pipe(
map(response => {
return boolean depending on the response
}),
catchError((err) => {
return throwError(err);
})
);
}
Test OK because it returns an error :
it('test', (done) => {
apiService.apiName.andCallFake(() => of(response));
spectator.service.myFonction('param1', 'param2')
.subscribe(
(res) => {
expect(res).toEqual(false); // should return an error because res = true
done();
},
() => fail()
);
}
Test KO because it doesn't return an error:
it('test', (done) => {
apiService.apiName.andCallFake(() => of(response));
spectator.service.myFunction('param1', 'param2')
.subscribe(
(res) => {
expect(res).toEqual(false); // should return an error because res = true
done();
},
() => fail()
);
--Modification of variables or not--
spectator.service.myFunction('param1', 'param2')
.subscribe(
(res) => {
expect(res).toEqual(true); // should not return an error because res = true
done();
},
() => fail()
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
