Skip to content

Instantly share code, notes, and snippets.

@RubenVerborgh
Last active December 11, 2015 01:38
Show Gist options
  • Save RubenVerborgh/4524424 to your computer and use it in GitHub Desktop.
Save RubenVerborgh/4524424 to your computer and use it in GitHub Desktop.
Demo implementation of eventually with flags.
(function (chaiModule) {
"use strict";
// NodeJS
if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
module.exports = chaiModule;
// AMD
else if (typeof define === "function" && define.amd)
define(function () { return chaiModule; });
// Other
else
chai.use(chaiModule);
}(function chaiAsPromised(chai, utils) {
"use strict";
var Assertion = chai.Assertion,
assertionPrototype = Assertion.prototype,
expect = chai.expect;
Assertion.addProperty("eventually", function () {
utils.flag(this, "eventually", { handled: false });
});
var methodNames = Object.getOwnPropertyNames(assertionPrototype)
.filter(function (propertyName) {
var property = Object.getOwnPropertyDescriptor(assertionPrototype, propertyName);
return typeof property.value === "function";
});
methodNames.forEach(function (methodName) {
Assertion.overwriteMethod(methodName, function (_super) {
return function () {
var eventuallyFlags = utils.flag(this, "eventually");
if (!eventuallyFlags || eventuallyFlags.handled)
return _super.apply(this, arguments);
eventuallyFlags.handled = true;
var object = utils.flag(this, "object");
expect(object).to.have.property("then");
expect(object.then).to.be.a("function");
var assertion = this,
args = arguments;
object.then(function (result) {
var assertionError;
utils.flag(assertion, "object", result);
try {
_super.apply(assertion, args);
}
catch (error) {
assertionError = error;
}
if (eventuallyFlags.notify)
eventuallyFlags.notify.call(assertion, assertionError);
eventuallyFlags.done = true;
eventuallyFlags.error = assertionError;
});
};
});
});
Assertion.addMethod("notify", function (callback) {
var eventuallyFlags = utils.flag(this, "eventually");
if (eventuallyFlags.done)
return callback(eventuallyFlags.error);
eventuallyFlags.notify = callback;
});
}));
#!/usr/bin/env node
var chai = require("chai");
var when = require("when");
chai.should();
chai.use(require(process.argv[2] || "./eventually-with-flags.js"));
var callbackCount = 1000;
for (var i = callbackCount; i > 0; i--)
when.resolve('x').should.eventually.equal('x').notify(function () {
if (!--callbackCount)
console.log('done');
});
@RubenVerborgh
Copy link
Author

$ time ./test.js 
done

real    0m0.377s
user    0m0.343s
sys     0m0.027s
$ time ./test.js chai-as-promised
done

real    0m7.848s
user    0m7.708s
sys     0m0.191s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment