diff --git a/src/main/PubSub.ts b/src/main/PubSub.ts index 2185cab..958717c 100644 --- a/src/main/PubSub.ts +++ b/src/main/PubSub.ts @@ -35,10 +35,11 @@ export class PubSub { /** * Waits for a message that satisfies the given predicate to be published and resolves with that message. * + * @template R A subtype of T that the predicate function identifies as satisfying the condition. * @param predicate A function that takes the message as a parameter and returns true if the message satisfies the condition, otherwise false. * @returns A promise that resolves with the published message that satisfies the predicate. */ - waitFor(predicate: (message: T) => boolean): Promise { + waitFor(predicate: (message: T) => message is R): Promise { return new Promise(resolve => { const unsubscribe = this.subscribe(message => { if (predicate(message)) { diff --git a/src/test/PubSub.test.ts b/src/test/PubSub.test.ts index 7b37fab..878618e 100644 --- a/src/test/PubSub.test.ts +++ b/src/test/PubSub.test.ts @@ -1,4 +1,4 @@ -import { PubSub, delay } from '../main'; +import { PubSub } from '../main'; describe('PubSub', () => { test('publishes a message', () => { @@ -55,41 +55,15 @@ describe('PubSub', () => { expect(listenerMock2).toHaveBeenCalledTimes(1); }); - test('waits for a specific message and resolves with that message', () => { + test('waits for a specific message and resolves with that message', async () => { const pubSub = new PubSub(); - - pubSub - .waitFor(message => message === 42) - .then(message => { - expect(message).toBe(42); - }); + const promise = pubSub.waitFor((message): message is 42 => message === 42); pubSub.publish(10); pubSub.publish(20); pubSub.publish(42); pubSub.publish(30); - }); - - test('does not resolve if no message matches the predicate', () => { - const listenerMock = jest.fn(); - const pubSub = new PubSub(); - - let result: number; - - pubSub - .waitFor(message => message === 42) - .then(message => { - result = message; - listenerMock(); - }); - - pubSub.publish(10); - pubSub.publish(20); - pubSub.publish(30); - delay(100).then(() => { - expect(result).toBeUndefined(); - expect(listenerMock).toHaveBeenCalledTimes(0); - }); + await expect(promise).resolves.toBe(42); }); });