简体   繁体   中英

Angular unit testing with RxJs: Introducing a delay in observable response

I am trying to unit test a function X. X calls another function,Y, which returns an observable. X calls Y several times. Code in X makes use of forkJoin to ensure that all the observables returned from Y are first completed. So I have to test that part too. I have mocked the call to Y as:

spyOn(anotherService, "Y").and.returnValues(of(data1), of(data2));

To make things a bit more realistic I want to introduce a delay in Y's response so that there is noticeable time gap between completion of first observable and second observable, so that forkJoin code in X is tested properly.

How can I introduce a delay here?

You can try using the delay operator but I would advise against doing so. You shouldn't be testing forkJoin , it has already been tested by the creators of RxJS.

But try doing this if you really want it:

import { delay } from 'rxs/operators';
.....
spyOn(anotherService, "Y").and.returnValues(of(data1), of(data2).pipe(delay(50)); // add a delay of 50ms like so

Usually, adding delays (or RxJs time functions) makes it tough to test because you might end up with One periodic tasks still in queue or other errors. You may have to take advantage of fakeAsync and tick if you don't want to wait the whole 50ms .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM