Skip to content

Commit

Permalink
add optional 2. arg to QUnit.raises qunitjs#69.
Browse files Browse the repository at this point in the history
  • Loading branch information
kof committed Dec 21, 2010
1 parent b4f59f6 commit 04ee7b0
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 17 deletions.
33 changes: 28 additions & 5 deletions qunit/qunit.js
Expand Up @@ -338,14 +338,37 @@ var QUnit = {
QUnit.push(expected !== actual, actual, expected, message);
},

raises: function(fn, message) {
raises: function(block, expected, message) {
var actual, ok = false;

if (typeof expected === 'string') {
message = expected;
expected = null;
}

try {
fn();
QUnit.ok( false, message );
block();
} catch (e) {
actual = e;
}
catch (e) {
QUnit.ok( true, message );

if (actual) {
// we don't want to validate thrown error
if (!expected) {
ok = true;
// expected is a regexp
} else if (QUnit.objectType(expected) === "regexp") {
ok = expected.test(actual);
// expected is a constructor
} else if (actual instanceof expected) {
ok = true;
// expected is a validation function which returns true is validation passed
} else if (expected.call({}, actual) === true) {
ok = true;
}
}

QUnit.ok(ok, message);
},

start: function() {
Expand Down
50 changes: 38 additions & 12 deletions test/test.js
Expand Up @@ -207,19 +207,45 @@ test("jsDump output", function() {
});

module("assertions");
test("raises", function() {
function thrower1() {
throw 'Errored!';
test("raises",function() {
function CustomError( message ) {
this.message = message;
}
function thrower2() {
throw new TypeError("Type!");
}
function thrower3() {
throw {message:"Custom!"};
}
raises(thrower1, 'Errored!', 'throwing string');
raises(thrower2, 'Type!', 'throwing TypeError instance');
raises(thrower3, 'Custom!', 'throwing custom object');

CustomError.prototype.toString = function() {
return this.message;
};



raises(
function() {
throw new CustomError();
},
CustomError,
'raised error is an instance of CustomError'
);

raises(
function() {
throw new CustomError("some error description");
},
/description/,
"raised error message contains 'description'"
);

raises(
function() {
throw new CustomError("some error description");
},
function( err ) {
if ( (err instanceof CustomError) && /description/.test(err) ) {
return true;
}
},
"custom validation function"
);

});

if (typeof document !== "undefined") {
Expand Down

0 comments on commit 04ee7b0

Please sign in to comment.