سؤال

I would like to implement optional async callbacks in same way as the mocha does.

I mean that I want to have callback function which can be both sync and async.

When user uses optional callback parameter 'done' it's async, when there is no callback parameter than it's synchronous.

// Sync version
it('does something sync', function() { 
  console.log('this is sync version') 
});

// Async version
it('does something async, function(done) {
  setTimeout(function() {
    done(true);
  }, 1000);
});

How can function 'it' distinguish if the callback is sync or async?

Any idea how to implement this?

هل كانت مفيدة؟

المحلول 2

If you can assume that the toString of your function hasn't been overridden, you could use it on a user-defined function to check if it has an argument named done, for example:

function argIndexOf(f, arg) {
  var s = f + '';
  return s.substring(s.indexOf('(') + 1, s.indexOf(')'))
    .replace(/\s+/g, '').split(',').indexOf(arg);
}

argIndexOf(function(){}, 'done'); // -1
argIndexOf(function(done){}, 'done') // 0
argIndexOf(function(arg1, done){}, 'done') // 1

That function would take in a function as an argument and return the position of it's done argument, or -1 if there is none. It uses Array.prototype.indexOf, which will need to be shimmed if you want to use it in IE 8 or earlier. You've tagged the question node.js, so I will assume that is not an issue.

You could even add it to Function.prototype, although this is highly discouraged if you want your code to play well with others:

Function.prototype.indexOf = Function.prototype.indexOf || function(arg) {
  var s = this + '';
  return s.substring(s.indexOf('(') + 1, s.indexOf(')'))
    .replace(/\s+/g, '').split(',').indexOf(arg);
};

Then you could just use:

func.indexOf('done')

You can also use apply and it will ignore negative indices, so to call the callback and pass in a value for 'done':

var args = [];
args[func.indexOf('done')] = done_callback;
func.apply(func, args);

نصائح أخرى

Mocha only checks for the existance of a callback parameter in the test function. function.length is used to determine how many parameters there are for the callback.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top