Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  142] [ 1]  / answers: 1 / hits: 46601  / 8 Years ago, sun, june 5, 2016, 12:00:00

In Mochajs, they use done() to test for asynchronous code, like so:



describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done) {
var user = new User('Luna');
user.save(function(err) {
if (err) throw err;
done();
});
});
});
});


What does this mean exactly? I did console.log(done.toString()) and I got this:



function (err) {
if (err instanceof Error || toString.call(err) === '[object Error]') {
return done(err);
}
if (err) {
if (Object.prototype.toString.call(err) === '[object Object]') {
return done(new Error('done() invoked with non-Error: '
+ JSON.stringify(err)));
}
return done(new Error('done() invoked with non-Error: ' + err));
}
done();
}


Is the done() at the very end here different than the done() in the first piece of code?


More From » node.js

 Answers
46

Mocha is able to handle synchronous and asynchronous tests. When you run a synchronous test, you can just pass it as an anonymous function to it and you don't have to do anything else: Mocha knows the test is over when the function returns. However, if you are running an asynchronous test, you have to tell Mocha that the test is asynchronous. There are two ways to do this:




  1. Declare that the anonymous function you pass to it takes a parameter. Mocha will call your anonymous function with a single parameter which is a function you must call to indicate that your test is over. (This parameter is called done due to tradition. You could call it complete, cb or platypus and it would work just the same.) If you call done without a value, the test is successful. With a value, the test is a failure and the value should be an Error object or an object derived from Error.


  2. Return a promise: Mocha will wait for the promise to be resolved or rejected. If resolved, the test is successful. If rejected, the test failed.




The code you see when you do done.toString() is just the code of the function that Mocha passes to your test when you declare it to take a parameter. You can see in it some of what I mentioned above (e.g. if you pass a parameter to done it should be an Error or derived from Error). The done in there is another done function which is private to Mocha.


[#61898] Thursday, June 2, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
havenbilliec

Total Points: 324
Total Questions: 106
Total Answers: 94

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;