Вот решение для модульного теста:
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));
});
});
Результаты модульного теста со 100% покрытием:
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