Mocha is a very good test framework for Javascript/nodejs, which natively supports synchronous and asynchronous testing, but asynchronous testing, because of the explicit invocation of the done (), can easily cause asynchronous code callback to be nested too deep, which is not conducive to understanding and maintaining test code:
It (' async test ', function (done) {
Dosomethinga (function (err, r1) {
//check ...
) DOSOMETHINGB (function (err, R2) {
//check ...
Done ();
});
});
});
So the man thought to test with ES6 's generator: Yield to the test:using Mocha with ES6 generators.
If you write the test code with generator, you can put it:
It (' Async test ', function* () {
var r1 = yield Dosomethinga ();
Check ...
var r2 = yield dosomethingb ();
Check ...
});
That's a good thing to write, but Mocha developers are not planning to introduce co to support generator, so the test code has to be changed to:
It (' async test ', function () {return
Co (function* () {
var r1 = yield Dosomethinga ();
Check ...
var r2 = yield dosomethingb ();
Check ...
});
});
Each testcase to write a few lines of identical code, naturally uncomfortable. So this man rewrote the mocha. Runnable.prototype.run:
Mocha. Runnable.prototype.run = function (fn) {
...
}
Have to say, this man's idea is very good, but changed the wrong place, the latest version of the Mocha 2.1.0 code and his revision has been very different, to change should also change the runnable constructor, so the smallest changes, and the simplest.
First, the source of the CO download a copy, named Co.js, and then modified:
Add:
var co = require ('./co ');
function Isgeneratorfunction (obj) {
var constructor = Obj.constructor;
Return constructor && ' generatorfunction ' = Constructor.name;
} End
function Runnable (title, fn) {
//new addition:
if (Isgeneratorfunction (FN)) {
var f = fn;
fn = function () {return
Co (f);
};
}//End
...
}
Isgeneratorfunction is copied from the source of Co. After the change is over, you can run the generator testcase directly.