diff --git a/src/lib/node.spec.ts b/src/lib/node.spec.ts index a7c918ec17..f1734b2cc8 100644 --- a/src/lib/node.spec.ts +++ b/src/lib/node.spec.ts @@ -1,6 +1,7 @@ import { TextDecoder, TextEncoder } from 'util'; import test from 'ava'; +import Pubsub from 'libp2p-interfaces/src/pubsub'; import { createNode } from './node'; @@ -10,36 +11,33 @@ function delay(ms: number) { test('Can publish message', async (t) => { const topic = 'news'; + const message = 'Bird bird bird, bird is the word!'; const [node1, node2] = await Promise.all([createNode(), createNode()]); // Add node's 2 data to the PeerStore node1.peerStore.addressBook.set(node2.peerId, node2.multiaddrs); await node1.dial(node2.peerId); - - let node1Received = ''; - - node1.pubsub.on(topic, (msg) => { - node1Received = new TextDecoder().decode(msg.data); - console.log(`node1 received: ${node1Received}`); - }); - await node1.pubsub.subscribe(topic); - - // Will not receive own published messages by default - node2.pubsub.on(topic, (msg) => { - console.log(`node2 received: ${new TextDecoder().decode(msg.data)}`); - }); - await node2.pubsub.subscribe(topic); - const message = 'Bird bird bird, bird is the word!'; + // Setup the promise before publishing to ensure the event is not missed + // TODO: Is it possible to import `Message` type? + const promise = waitForNextData(node1.pubsub, topic).then((msg: any) => { + return new TextDecoder().decode(msg.data); + }); - await delay(1000); + await delay(500); await node2.pubsub.publish(topic, new TextEncoder().encode(message)); - await delay(1000); + const node1Received = await promise; t.deepEqual(node1Received, message); }); + +function waitForNextData(pubsub: Pubsub, topic: string) { + return new Promise((resolve) => { + pubsub.once(topic, resolve); + }); +}