From 04ee7b0994c64b37d9358f4003105ae36e72e292 Mon Sep 17 00:00:00 2001 From: "Oleg Slobodskoi @oleg008" Date: Tue, 21 Dec 2010 16:53:32 +0100 Subject: [PATCH] add optional 2. arg to QUnit.raises #69. --- qunit/qunit.js | 33 ++++++++++++++++++++++++++++----- test/test.js | 50 ++++++++++++++++++++++++++++++++++++++------------ 2 files changed, 66 insertions(+), 17 deletions(-) diff --git a/qunit/qunit.js b/qunit/qunit.js index caf473316..e1b12ce61 100644 --- a/qunit/qunit.js +++ b/qunit/qunit.js @@ -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() { diff --git a/test/test.js b/test/test.js index b5f62fd0e..62a46a2f2 100644 --- a/test/test.js +++ b/test/test.js @@ -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") {