diff --git a/test/Event.spec.ts b/test/Event.spec.ts index 94bceb0..d70d472 100644 --- a/test/Event.spec.ts +++ b/test/Event.spec.ts @@ -2,6 +2,7 @@ import { slot } from './../src/Slot' import { combineEvents, createEventBus } from './../src/Events' import { TestChannel } from './TestChannel' import { DEFAULT_PARAM } from './../src/Constants' +import { flushPromises } from './testing-utils' describe('combineEvents()', () => { @@ -93,7 +94,7 @@ describe('createEventBus()', () => { data: 5 }) - await Promise.resolve() // yied to ts-event-bus internals + await flushPromises() expect(channel.sendSpy).toHaveBeenCalledWith({ type: 'response', slotName: 'numberToString', diff --git a/test/Slot.spec.ts b/test/Slot.spec.ts index 85c8fed..01e3322 100644 --- a/test/Slot.spec.ts +++ b/test/Slot.spec.ts @@ -3,6 +3,7 @@ import { TestChannel } from './TestChannel' import { Transport } from './../src/Transport' import { DEFAULT_PARAM } from './../src/Constants' import { TransportRegistrationMessage } from './../src/Message' +import { flushPromises } from './testing-utils' const makeTestTransport = () => { const channel = new TestChannel() @@ -145,9 +146,7 @@ describe('connectSlot', () => { type: 'handler_registered' }) - // setTimeout(0) to yield control to ts-event-bus internals, - // so that the call to handlers can be processed - await new Promise(resolve => setTimeout(resolve, 0)) + await flushPromises() // Once a remote handler is registered, both local and remote should be called expect(localCalled).toEqual(true) diff --git a/test/Transport.spec.ts b/test/Transport.spec.ts index 305cbf5..d05d23f 100644 --- a/test/Transport.spec.ts +++ b/test/Transport.spec.ts @@ -1,6 +1,7 @@ import { Transport } from './../src/Transport' import { TransportMessage } from './../src/Message' import { TestChannel } from './TestChannel' +import { flushPromises } from './testing-utils' const param = 'param' @@ -89,7 +90,7 @@ describe('Transport', () => { channel.fakeReceive(request) - await Promise.resolve() // yield to ts-event-bus internals + await flushPromises() expect(handler).toHaveBeenCalledWith(request.data) expect(channel.sendSpy).toHaveBeenLastCalledWith({ slotName, @@ -141,7 +142,7 @@ describe('Transport', () => { } } channel.fakeReceive(request) - await Promise.resolve() // yield to ts-event-bus internals + await flushPromises() expect(handler).not.toHaveBeenCalled() }) diff --git a/test/testing-utils.ts b/test/testing-utils.ts new file mode 100644 index 0000000..5f14c46 --- /dev/null +++ b/test/testing-utils.ts @@ -0,0 +1,6 @@ +/** + * Utility to flush current promises during a test when using fake timers + */ +export function flushPromises(): Promise { + return new Promise(jest.requireActual('timers').setImmediate) +}