Skip to content

Commit

Permalink
A refactoring that I'm more happy with.
Browse files Browse the repository at this point in the history
  • Loading branch information
domenic committed Mar 25, 2012
1 parent 84df6a3 commit b1561a0
Showing 1 changed file with 18 additions and 24 deletions.
42 changes: 18 additions & 24 deletions lib/promised-chai.js
Expand Up @@ -183,60 +183,54 @@
return transformedPromise;
});

function assertionFromFulfillment(fulfillmentValue) {
if (fulfillmentValue instanceof Assertion) {
var assertion = new Assertion(fulfillmentValue.obj);
assertion.negate = fulfillmentValue.negate;
return assertion;
} else {
return new Assertion(fulfillmentValue);
}
}

function onFulfilledFactory(assertion) {
return function (fulfillmentValue) {
function promiseWithAsserters(promise, originalAssertion) {
function makeAssertion(fulfillmentValue) {
var newAssertion = null;

if (fulfillmentValue instanceof Assertion) {
newAssertion = new Assertion(fulfillmentValue.obj);
newAssertion.negate = fulfillmentValue.negate;
} else {
newAssertion = new Assertion(fulfillmentValue);
newAssertion.negate = assertion.negate;
newAssertion.negate = originalAssertion.negate;
}

return newAssertion;
};
}

function promiseWithAsserters(promise, assertion) {
// Create an extensible copy of the assertion's promise, so we can add all the asserters to it.
var promise = Object.create(promise);
function promiseToDoAsserter(doAsserter) {
var promiseForAssertion = promise.then(makeAssertion);
var basicPromiseToDoAsserter = promiseForAssertion.then(doAsserter);
var promiseToDoAsserterWithAsserters = promiseWithAsserters(basicPromiseToDoAsserter, originalAssertion);

// Get all of Chai's asserters and add versions of them that return promises to assert on the eventual value.
return promiseToDoAsserterWithAsserters;
}

var augmentedPromise = Object.create(promise);
var asserterNames = Object.getOwnPropertyNames(Assertion.prototype);
asserterNames.forEach(function (asserterName) {
var propertyDescriptor = Object.getOwnPropertyDescriptor(Assertion.prototype, asserterName);

if (propertyDescriptor.value) {
propertyDescriptor.value = function () {
var args = arguments;
return promiseWithAsserters(promise.then(onFulfilledFactory(assertion)).then(function (assertion) {

return promiseToDoAsserter(function (assertion) {
return assertion[asserterName].apply(assertion, args);
}), assertion);
});
};
} else if (propertyDescriptor.get) {
propertyDescriptor.get = function () {
return promiseWithAsserters(promise.then(onFulfilledFactory(assertion)).then(function (assertion) {
return promiseToDoAsserter(function (assertion) {
return assertion[asserterName];
}), assertion);
});
};
}

Object.defineProperty(promise, asserterName, propertyDescriptor);
Object.defineProperty(augmentedPromise, asserterName, propertyDescriptor);
});

return promise;
return augmentedPromise;
}

property("eventually", function () {
Expand Down

0 comments on commit b1561a0

Please sign in to comment.