Girdhar Sojitra
Girdhar Sojitra

Reputation: 678

How can i receive more than one event of same type using Event Emitter?

I am writing testcase using mocha framework.I have to write testcase in which i want to receive more than one event of same type and check all the event values against expected value.I am using EventEmitter for emitting events but i don't know how to accumulate more than one event at a time and then check all the value in one context.

How events can be aggregated/accumulated using eventEmitter or by any other means ?

Upvotes: 1

Views: 482

Answers (1)

danroshko
danroshko

Reputation: 466

You can just create an empty array to hold the emitted values and whenever a new event is emitted, push it to the array and check its length. When array length is equal to the number of events that you expect, perform all the checks that you need. If you need that functionality in multiple tests, it can be extracted into a separate function. Look at the collect function in the following example:

// waits for specified number of events and then resolves with the results
function collect(emitter, event, count) {
    const results = [];

    return new Promise((resolve, reject) => {
        emitter.on(event, value => {
            results.push(value);
            if (results.length === count) {
                 return resolve(results);
            }
        })
    })
}

describe('EventEmitter', function() {
    it('emits 3 ping events', function() {
        const emitter = new EventEmitter();

        setTimeout(() => {
            emitter.emit('ping', 'pong');
            emitter.emit('ping', 'pong');
            emitter.emit('ping', 'pong');
        }, 10)

        return collect(emitter, 'ping', 3).should.eventually.eql(['pong', 'pong', 'pong']);
    })
})

Upvotes: 1

Related Questions