Skip to content

Commit

Permalink
Added flag that, when set to true, makes sinon.logError throw errors …
Browse files Browse the repository at this point in the history
…synchronously.

Fix #172: sinon.logError should throw synchronously instead of after a timeout
  • Loading branch information
D1SoveR committed Aug 31, 2015
1 parent c2e25c4 commit 288b363
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 4 deletions.
18 changes: 14 additions & 4 deletions lib/sinon/log_error.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,28 @@
function logError(label, err) {
var msg = label + " threw exception: ";

function throwLoggedError() {
err.message = msg + err.message;
throw err;
}

sinon.log(msg + "[" + err.name + "] " + err.message);

if (err.stack) {
sinon.log(err.stack);
}

logError.setTimeout(function () {
err.message = msg + err.message;
throw err;
}, 0);
if (logError.useImmediateExceptions) {
throwLoggedError();
} else {
logError.setTimeout(throwLoggedError, 0);
}
}

// When set to true, any errors logged will be thrown immediately;
// If set to false, the errors will be thrown in separate execution frame.
logError.useImmediateExceptions = false;

// wrap realSetTimeout with something we can stub in tests
logError.setTimeout = function (func, timeout) {
realSetTimeout(func, timeout);
Expand Down
38 changes: 38 additions & 0 deletions test/log-error-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
var buster = root.buster || require("buster");
var sinon = root.sinon || require("../lib/sinon");
var assert = buster.assert;
var refute = buster.refute;

buster.testCase("sinon.log", {
"is a function": function () {
Expand Down Expand Up @@ -72,4 +73,41 @@
assert.exception(func);
}
});

buster.testCase("sinon.logError.useImmediateExceptions", {
setUp: function () {
this.sandbox = sinon.sandbox.create();
this.timeOutStub = this.sandbox.stub(sinon.logError, "setTimeout");
this.originalFlag = sinon.logError.useImmediateExceptions;
},

tearDown: function () {
// setTimeout = realSetTimeout;
this.sandbox.restore();
sinon.logError.useImmediateExceptions = this.originalFlag;
},

"throws the logged error immediately, does not call logError.setTimeout when flag is true": function () {

var error = new Error();

sinon.logError.useImmediateExceptions = true;

assert.exception(function () {
sinon.logError("an error", error);
});
assert(this.timeOutStub.notCalled);
},

"does not throw logged error immediately and calls logError.setTimeout when flag is false": function () {
var error = new Error();

sinon.logError.useImmediateExceptions = false;

refute.exception(function () {
sinon.logError("an error", error);
});
assert(this.timeOutStub.called);
}
});
}(this));

0 comments on commit 288b363

Please sign in to comment.