How can I pass mochas done callback function to an

2019-08-13 02:30发布

问题:

I have a block of code that I will be using several times within a then statement in mocha so I turned it into a function. However I also need to call done()within that function and it's out of scope resulting in the error Uncaught ReferenceError: done is not defined. Here's a code snippet:

var collectionChecker = function(results) {
  expect(Array.isArray(results), 'Did not return collection');
  expect(results.length === numAttr, 'Returned wrong number of models');
  done();
};

test('returns a collection with correct number of models', function(done) {
  attrs.getAttributeTemplates().then(collectionChecker);
});

How can I pass done() to my function?

I found a workaround by chaining another .then and calling done there but it seems like an ugly way to do it.

回答1:

You're overthinking it - mocha supports promises, you can return a promise and if it is fulfilled the test will pass (and if the expects throw it will fail):

var collectionChecker = function(results) {
  expect(Array.isArray(results), 'Did not return collection');
  expect(results.length === numAttr, 'Returned wrong number of models');
};

// just add a return, no `done` here or anywhere    
test('returns a collection with correct number of models', function() {
  return attrs.getAttributeTemplates().then(collectionChecker);
});