title: NodeJS EventEmitter test with Mocha
body: <p>I have a problem testing <a href="http://ldapjs.org/client.html#search" rel="nofollow noreferrer">ldapjs</a> client search operation. It returns an EventEmitter that you have to make listen for some specific event. I wrapped this operations to promisify it and to define my logic and I would like to unit-test it. </p>
  
  <pre><code>findUser(username) {
      return new Promise((resolve, reject) =&gt; {
          logger.debug('Searching user: ', username);
          this.ldapClient.bind(user.name, .user.password, err =&gt; {
              if (err) return reject(err);
              else
                  this.ldapClient.search(root, {filter: `(cn=${username})`}, (errSearch, resSearch) =&gt; {
                      if (errSearch) return reject(errSearch);
                      const entries = [];
                      resSearch.on('searchEntry', entry =&gt; entries.push(entry.object));
                      resSearch.on('searchReference', referral =&gt; reject(new Error(`Received search referall: ${referral}`)));
                      resSearch.on('error', err =&gt; reject((err));
                      resSearch.on('end', result =&gt; {
                          if (result.status === 0 &amp;&amp; entries.length === 1) {
                              return resolve({
                                  cn: entries[0].cn,
                                  objectclass: entries[0].objectclass,
                                  password: entries[0].password
                              });
                          } else {
                              return reject(new Error(`Wrong search result: ${result}`));
                          }
                      });
                  });
          });
      });
  }
  </code></pre>
  
  <p>I am using <a href="https://github.com/mfncooper/mockery" rel="nofollow noreferrer">mockery</a> and <a href="http://sinonjs.org/" rel="nofollow noreferrer">Sinon</a> to replace ldapjs dependency inside my module:</p>
  
  <pre><code>beforeEach(function () {
      searchEM = new EventEmitter();
      sandbox = sinon.createSandbox();
      ldapClientStub = Stubs.getLdapClientStub(sandbox);
      ldapClientStub.bind.yields(null);
      ldapClientStub.search.withArgs('o=ldap', {filter: `(cn=${findParam})`}).yields(null, searchEM);
  
      mockery.registerMock('ldapjs', Stubs.getLdapStub(ldapClientStub));
      mockery.registerAllowable('../src/client');
  
      UserClientCls = require('../src/client').default;
      userClient = new UserClientCls(config.get());
  });
  
  it('should return user with given username', function (done) {
      setTimeout(() =&gt; {
          searchEM.emit('searchEntry', users[1]);
          searchEM.emit('end', {status: 0});
          console.log('emitted');
      }, 500);
      searchEM.on('end', res =&gt; console.log(res));
  
      userClient.findUser(findParam)
          .then(user =&gt; {
              user.cn.should.equal(users[1].attributes.cn);
              user.objectclass.should.equal(users[1].attributes.objectclass);
              user.password.should.equal(users[1].attributes.password);
              return done();
          })
          .catch(err =&gt; done(err));
  });
  </code></pre>
  
  <p>The problem is that listeners defined inside <code>findUser</code> are never called (but the function itself is called). The listener I defined in the test (just to debug the behaviour) is correctly called.</p>
  
  <p>I do not understand if I miss something about how EventEmitters works or if I am doing the test in a wrong way. Or maybe I wrote a bad piece of code that cannot be tested.</p>