Testing for exceptions

16 views
Skip to first unread message

Stefan Pöter

unread,
Oct 8, 2011, 9:13:43 AM10/8/11
to google-...@googlegroups.com
Hi,

i've got a problem when testing for exceptions.

Maybe i missunderstood something here but shouldn't this example be a valid test?

var throwException = function() {
  throw {
    name: 'SomeException'
  }
}

expectThat(throwException(), throwsError());

gjstest prints out an error:
[object Object]

Thanks,
Stefan

Aaron Jacobs

unread,
Oct 9, 2011, 6:06:48 PM10/9/11
to google-...@googlegroups.com
Hi Stefan,

On Sun, Oct 9, 2011 at 12:13 AM, Stefan Pöter
<stefan...@googlemail.com> wrote:
> expectThat(throwException(), throwsError());

There are a couple of things wrong here: the subject of the expectation should
be a function, not a call to that function, and `throwsError` takes a regular
expression describing the error. So it should look like this:

expectThat(throwException, throwsError(/foo.*bar/));

This works correctly if the error thrown is instantiated from one of the
built-in types (for example by saying `new TypeError('foo bar')`). Since
`throwsError` looks at the string form of the error but your error object
doesn't have a helpful `toString` method, it won't work for your custom error,
however.

I've filed two issues to make the output more helpful when the user makes
these mistakes:

http://code.google.com/p/google-js-test/issues/detail?id=16
http://code.google.com/p/google-js-test/issues/detail?id=17

Aaron

Stefan Pöter

unread,
Oct 10, 2011, 3:21:26 AM10/10/11
to google-...@googlegroups.com
Hi Aaron,

thanks for your reply.

In that case i've written my own matcher looking like this:

throwsException = function(params, re) {
var description = 'is a function that throws an exception matching ' + re + ' with parameters' + params;
var negativeDescription = 'is a function that throws an exception not matching ' + re + ' with parameters ' + params;

var p = (typeof(params) === 'array' && params.length) ? params : [];
var r = (typeof(params) === 'string') ? params : re;

return new gjstest.Matcher(
description,
negativeDescription,
function(fnct) {
try {
fnct.apply(null, p);
expectTrue(false);
} catch(e) {
if (new RegExp(r).test(e.name)) {
return true;
}

return 'which threw wrong exception ' + e.name;
}

return 'which threw no exceptions';
}
);
};


Greetings
Stefan

Stefan Pöter

unread,
Oct 10, 2011, 3:29:21 AM10/10/11
to google-...@googlegroups.com
Ok, short explanation :-)


simply do

var fnct = function(a, b) {
  throw {
    name : 'SomeException'
  }
}

expectThat(fnct, throwsException([1, 2], 'SomeException'))

Aaron Jacobs

unread,
Oct 10, 2011, 4:55:04 PM10/10/11
to google-...@googlegroups.com
On Mon, Oct 10, 2011 at 6:21 PM, Stefan Pöter
<stefan...@googlemail.com> wrote:
> In that case i've written my own matcher looking like this:

Great! This may be the first public user-written matcher. :-)

Aaron

Reply all
Reply to author
Forward
0 new messages