I have the following service:
export class MathService {
private _total = new BehaviorSubject(0);
total$ = this._total.asObservable();
add(num: number) {
this._total.next(this._total.value() + num);
}
subtract(num: number) {
this._total.next(this._total.value() - num);
}
}
How would you test that total$
emits the correct values in a sequence of add
and subtract
function calls like this:
service.add(10) // should emit 10;
service.subtract(3) // should emit 7;
service.add(20) // should emit 27;
service.subtract(5) // should emit 22;
...
Would marble test work for something like this? If so, how would you set that up? I wasn't able to find a clear example online of how to test that an observable on a service emits the proper sequence of values given a sequence of function calls on that service?
First of all I would try to test without marble diagrams, just to make sure we understand how the asyn execution would work.
Once the async mechanism is clear, then we can look at an implementation which uses marble diagrams, like this one
This implementation follows some examples of tests used in the rxJs library.
The implmentation of
observableMatcher
can be seen here.