laketuna
laketuna

Reputation: 4090

Mocha: how to test this async method that returns a callback?

I'd like to run a unit-test for a method like below.

returnsCallback (callback) {
  return callback(null, false)
}

The callback arguments being passed in are, I believe, (error, response). I can't figure out how to test this or if it's even appropriate to test. Do I mock the callback argument to test it? I have below so far, and it seems to work, but I'm not sure. Any ideas?

describe('returnsCallback ()', function () {
  let myObj = new MyObject()

  it ('should always return false', function (done) {
    myObj.returnsCallback(function (error, response) {
      if (!error && response === false) {
        done(false)
      } else {
        done(true)
      }
    })
  })
})

Upvotes: 0

Views: 94

Answers (1)

alexmac
alexmac

Reputation: 19617

You should test not that callback returns false, but that it's called with correct parameters. In your case they are null and false. I don't know what assertion library do you use, I show an example with using should module:

describe('returnsCallback ()', () => {
  let myObj = new MyObject();

  it ('should call callback with error is null and response is false', done => {
    myObj.returnsCallback((error, response) => {
      should(error).be.exactly(null);
      should(response).be.equal(true);
      done();
    });
  });
});

Upvotes: 1

Related Questions