简体   繁体   中英

NodeUnit - Testing an asynchronous function

I want to tests the results returned by an asynchronous function with nodeunit . I have the following test :

module.exports = {
  createFail: function(assert) {
    var user = new CRUDUser({ firstName: 'Node' });

    assert.equal(undefined, user.id);

    user.create(function(res) { // user.create() makes an async AJAX call and should call this function back
      assert.equal(false, res.success);
      assert.equal(undefined, user.id); // user not created cause 'lastName' can't be null

      console.log('#####');
      assert.done();
    });
  }
};

But when I run it I get the following error :

FAILURES: Undone tests (or their setups/teardowns): 
- createFail

To fix this, make sure all tests call test.done()

If I move the assert.done(); call outside the callback function, the test ends up before the AJAX call has been made.

I also tried to add assert.expect(3); at the very beginning of the test to make it "wait" until the callback function calls assert.done(); but I get the same error as above.

In all cases, the expected ##### isn't outputed to the console obviously. What am I doing wrong ??

Based on your output, my first theory is that user.create is simply not ever calling the callback function. Debug into that and make sure in all cases (success, failure, timeout, etc), it actually invokes the callback function. In other words, your test code looks probably OK but the code you are testing is suspect of having a bug.

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