Akheloes
Akheloes

Reputation: 1372

Testing anonymous async function inside of an RxJS from

I am failing to find a way of testing the following function:

  public toTest(): Observable<boolean> {
    return from(
      async(): Promise<boolean> => {
        return new Promise(resolve => { resolve(true); });
      }
    );
  }

Thus far, I've tried something along the usual:

  it('coverage toTest()', async (done) => {
    testeeObject.toTest().subscribe(
      result => {
        done();
      }
    );
  });

The coverage is as follows:

enter image description here

How may I conceive a test to get the coverage of this function ?

Note: rewriting the function should be the very last proposition to consider. This is not the real code, I've simplified to make a generic example, the anonymous async function has some more code into it, naturally.

Upvotes: 1

Views: 658

Answers (1)

Lin Du
Lin Du

Reputation: 102587

You can use jest.mock(moduleName, factory, options) to mock rxjs package, and mockFn.mockImplementationOnce(fn) to mock the implementation of from operator for rxjs.

index.ts:

import { from, Observable } from 'rxjs';

class MyClass {
  public toTest(): Observable<boolean> {
    return from(
      async (): Promise<boolean> => {
        return new Promise((resolve) => {
          resolve(true);
        });
      },
    );
  }
}

export { MyClass };

index.test.ts:

import { MyClass } from './';
import { from } from 'rxjs';

jest.mock('rxjs', () => {
  return { from: jest.fn() };
});

describe('61272624', () => {
  it('should pass', async () => {
    const myclass = new MyClass();
    let input: () => Promise<boolean>;
    const fromMock: any = (o) => {
      // We can get the async function you passed in `from` operator. 
      // Let the input variable keep it, we will execute it later.
      input = o; 
    };
    (from as jest.MockedFunction<typeof from>).mockImplementationOnce(fromMock);
    myclass.toTest();
    const actual = await input!();
    expect(actual).toBeTruthy();
  });
});

unit test results with coverage report:

 PASS  stackoverflow/61272624/index.test.ts (13.553s)
  61272624
    ✓ should pass (4ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        15.565s

enter image description here

source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61272624

Upvotes: 2

Related Questions