Skip to content

Commit

Permalink
Review fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
dPaskhin committed May 6, 2024
1 parent 5935fa3 commit d780253
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 31 deletions.
3 changes: 2 additions & 1 deletion src/main/PubSub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,11 @@ export class PubSub<T = void> {
/**
* 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<T> {
waitFor<R extends T>(predicate: (message: T) => message is R): Promise<R> {
return new Promise(resolve => {
const unsubscribe = this.subscribe(message => {
if (predicate(message)) {
Expand Down
34 changes: 4 additions & 30 deletions src/test/PubSub.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PubSub, delay } from '../main';
import { PubSub } from '../main';

describe('PubSub', () => {
test('publishes a message', () => {
Expand Down Expand Up @@ -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<number>();

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<number>();

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);
});
});

0 comments on commit d780253

Please sign in to comment.