How to test EventEmitter in NodeJS?

We are using NodeJS built-in event emitter to send events to a websocket server instance to make some action and we wanted to test that connection. Testing websockets is pretty simple but also slow. You have to register some clients to the socket and make some action happen. Also that requires that you manually call the done function of the mocha test library. So we left 1-2 tests for the websocket connection but we focused on testing the Event Emitter.

Our problem was that tests are run asynchronously and if an action happens for which 2 tests are listening they both will be notified and that may break some tests. So we found the solution online and it is called Sinon. With it you can create so called spies and you can easily test the event emitter even if the tests are asynchronous.

Here is a sampe test:


 it('Should receive refresh event when collection is created', function* () {
        var user1Id = (yield dbHelper.createUser())
        var user2Id = (yield dbHelper.createUserWithEmail("asdasda"))
        var collectionId = (yield dbHelper.createAppsCollection(user1Id))

        var spy = sinon.spy()
        EventEmitter.on('refresh', spy)

        var appIds = yield dbHelper.createFourAppsWithIds(user1Id)

        yield dbHelper.followUser(user1Id, user2Id)
        yield dbHelper.makeCollectionPublic(user1Id, collectionId, appIds)

        sinon.assert.calledWith(spy, {interestedUsers: [user2Id]});

You may also like...