mahadev gouda
mahadev gouda

Reputation: 119

How to test void functions using jest

I have a function that returns nothing. How can we write the jest test cases to verify this function?

onSilentTrackReadyToPlay(callback: (trackState: string) => void): void {
    this.trackReadySubscription = this.MediaPlayerEventEmitter.addListener(
      'silentTrackReadyToPlay',
      (trackState) => {
        if (callback) {
          callback(trackState)
        }
      },
    )
  }

Upvotes: 1

Views: 7080

Answers (1)

Lin Du
Lin Du

Reputation: 102327

Here is the unit test solution:

index.ts:

export class SomeClass {
  private MediaPlayerEventEmitter;
  private trackReadySubscription;
  constructor(MediaPlayerEventEmitter) {
    this.MediaPlayerEventEmitter = MediaPlayerEventEmitter;
  }
  onSilentTrackReadyToPlay(callback?: (trackState: string) => void): void {
    this.trackReadySubscription = this.MediaPlayerEventEmitter.addListener('silentTrackReadyToPlay', (trackState) => {
      if (callback) {
        callback(trackState);
      }
    });
  }
}

index.test.ts:

import { SomeClass } from './';

describe('60617618', () => {
  it('should call callback if exists', () => {
    const mMediaPlayerEventEmitter = {
      addListener: jest.fn().mockImplementationOnce((event, handler) => {
        handler();
      }),
    };
    const ins = new SomeClass(mMediaPlayerEventEmitter);
    const callback = jest.fn();
    ins.onSilentTrackReadyToPlay(callback);
    expect(mMediaPlayerEventEmitter.addListener).toBeCalledWith('silentTrackReadyToPlay', expect.any(Function));
    expect(callback).toBeCalledWith(undefined);
  });

  it('should do nothing if callback does not exist', () => {
    const mMediaPlayerEventEmitter = {
      addListener: jest.fn().mockImplementationOnce((event, handler) => {
        handler();
      }),
    };
    const ins = new SomeClass(mMediaPlayerEventEmitter);
    ins.onSilentTrackReadyToPlay();
    expect(mMediaPlayerEventEmitter.addListener).toBeCalledWith('silentTrackReadyToPlay', expect.any(Function));
  });
});

unit test results with 100% coverage:

 PASS  stackoverflow/60617618/index.test.ts (8.883s)
  60617618
    ✓ should call callback if exists (4ms)
    ✓ should do nothing if callback does not exist

----------|---------|----------|---------|---------|-------------------
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:       2 passed, 2 total
Snapshots:   0 total
Time:        10.307s

Upvotes: 2

Related Questions