简体   繁体   中英

What's wrong with this unit test of an async JavaScript function (via Mocha/Sinon)?

I was trying to put together a small example to show co-workers but can't figure out what's wrong with this test that I've put in a gist .

Essentially I want to test a function that does something async, but use Sinon's spy() functionality to assure it completes:

function asyncHello(name, delay, cb) {
  setTimeout(function() {
    console.log("running after ", delay);
    cb("hello " + name);
  }, delay);
}



suite('Mega Suite', function(){

  suite("testing async hello", function() {
    test('should call the callback', function(done) {
      var cb = sinon.spy();
      asyncHello("foo", cb);

      cb.should.have.been.called();
      done();
    });
  });
});

Thought using Mocha and done() to resolve a test that depends on an async function (setTimeout, in this case) would work, but maybe someone can point out where I'm wrong. Thanks!

You don't need Sinon for this:

function asyncHello(name, delay, cb) {
  setTimeout(function() {
    console.log("running after ", delay);
    cb("hello " + name);
  }, delay);
}

suite('Mega Suite', function(){
  suite("testing async hello", function() {
    test('should call the callback', function(done) {
      asyncHello("foo", 1000, function () {
        done();
      });
    });
  });
});

There were two problems in this code:

  1. You called asyncHello("foo", cb); which made it so that your delay argument inside the function was set to cb and the cb argument inside the function was undefined.

  2. Even after fixing the 1st item cb.should.have.been.called(); was called before the function passed to setTimeout could execute.

    You basically don't need to use Sinon because if you just set a callback to call done() then you know the test is successful. If there's a problem anywhere done() won't get called and the test will fail.

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