简体   繁体   中英

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)
      }
    })
  })
})

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();
    });
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM