Skip to content

Add ability to flush pending message queue #51

@Coteh

Description

@Coteh

I am currently utilizing this library to mock communication between my frontend app and an IRC gateway called webircgateway for my unit tests, and I wasn't able to find a function that can clear out the pending message queue within a test. I am testing whether my app can send out a message, and I currently have to copy and paste await server.nextMessage so that I can discard the IRC initial communication messages (PASS, NICK, and USER) which I don't care about so that I can then call toReceiveMessage and toHaveReceivedMessages on the PRIVMSG message, which I do care about.

I attempted to make my own makeshift flush function:

async function flushWebSocketMessages(server: WS) {
    while (1) {
        const result = await promiseWithTimeout(server.nextMessage);
        if (result === null) {
            break;
        }
    }
}

function promiseWithTimeout<T>(promise: Promise<T>) {
    return new Promise((resolve, reject) => {
        promise
            .then((val) => resolve(val))
            .catch((err) => reject(err));

        setTimeout(() => {
            resolve(null);
        }, 2000);
    });
}

However, it does not seem to work because once I clear out the queue (which happens when we cannot get any more messages and the 2s timeout returns null) any message I send through the WebSocket is reported by the mock server as undefined:

 expect(WS).toReceiveMessage(expected)

    Expected the next received message to equal:
      "PRIVMSG #mychannel :Hello there"
    Received:
      undefined

    Difference:

      Comparing two different types of values. Expected string but received undefined.

I have decided to work around this for the time being by copy and pasting await server.nextMessage like I mentioned earlier in order to clear out the queue, but I would like to know why this is happening if possible. Also, let me know if flushing the pending message queue is something that can benefit this project, thanks.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions