How to mock/simulate in the jest test PubNub event which added in pubnub.addListener?

293 Views Asked by At

I have a package that uses PubNub, I', try to cover all package files with jest tests, but I have a problem: I can't find the way to cover events inside the listener

    // add listener
    const listener = {
        // Need to cover these cases (status and message)
        status: (statusEvent) => {
            if (statusEvent.category === "PNConnectedCategory") {
                console.log("Connected");
            }
        },
        message: (messageEvent) => {
            // Process message
        }
    };

    this.pubnub.addListener(listener);

    this.pubnub.subscribe({
        channels: [this.channel]
    });

I attached a screen with the part which I need to cover test [![uncovered file part][1]][1] How to mock/simulate in the jest test PubNub event which added in pubnub.addListener?

describe("publishPubNub test suites", () => {  
        const sideEffect = function (options) {
            pubnubService.publishPubNub(options);
            return true;
        } 

        it("successfull", () => {
            //TODO: mock event here
            const isCompleted =  sideEffect(publishPubNubOptions)
            expect(isCompleted).toBeTruthy();
        });
    })

Thanks for any helps or advice. [1]: https://i.stack.imgur.com/tF3c2.png

1

There are 1 best solutions below

0
Darryn Campbell On

The listener status handler will be invoked whenever a connection is established (or some other connection event happens). The message handler will be invoked whenever your application receives a message that it has previously subscribed to.

You could either:

  1. Test your application against a real PubNub instance, though that would require an Internet connection.

  2. Create a mocked library. PubNub does not offer an official mocked library so you would need to roll your own. Something like the following based on your image:

'use strict';
class PubNub {
    constructor(pubKey, subKey, uniqueId) {
        this.listener = {}
    }
    addListener(listener) {
        this.listener = listener;
    }
    subscribe(channelsObj) {
        this.listener.status({"category": "PNConnectedCategory"})
    }
    publishPubNub(options) {
        this.listener.message({"message": {"request": {"decision": "approved"}}})
    }
}
module.exports = PubNub;