K
K
kserg9032019-12-23 16:40:55
JavaScript
kserg903, 2019-12-23 16:40:55

How to test an async function that uses forkJoin?

There is a function like this:

public method1(): Observable<any> {
  return forkJoin({
    var1: // some var,
    var2: // some var,
    var3: // some var,
    var4: // some var,
    var5: // some var,
    var6: // some var,
  }).pipe(
    switchMap(data => {
      const res = {
        var1: data.var1,
        var2: data.var2,
        var3: data.var3,
        var4: data.var4,
        var5: data.var5,
        var6: data.var6,
      };
      return of(res);
    }),
  );
}

It makes 6 asynchronous requests and combines the result into one object. I would like to write a unit test for it. Here is my attempt:
it('should works', fakeAsync(() => {
  component.MyComponent().subscribe(data => {
    expect(data.var1).toEqual(mock1);
    expect(data.var2).toEqual(mock2);
    expect(data.var3).toEqual(mock3);
    expect(data.var4).toEqual(mock4);
    expect(data.var5).toEqual(mock5);
    expect(data.var6).toEqual(mock6);
    tick();
    discardPeriodicTasks();
    component.ngOnDestroy();
  });
}));

The problem is that after running the tests, the console displays the following error message:
FAIL: 6 periodic timer(s) still in the queue.

I understand that 6 requests are asynchronous, so I wrap the test body in fakeAsync().
I understand that the test should wait until all 6 requests that are in the forkJoin are completed. That's why I use tick().
But all the same the test does not fulfill. Please help me fix it

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question