简体   繁体   中英

Can someone please provide a really simple full example of assertException using jsTestDriver.js

I come from a heavy C# background and am currently learning my way through ASP.NET MVC with Knockout.js and JavaScript. I'm very much a TDD based person and have hit a number of snags which I seem to be struggling with. I've read a number of examples of jsTestDriver and all seem fairly straightforward until put to the test...

Basically, what I'm trying to unit test (using JetBrains WebStorm 5.0.4 in conjunction with JsTestDriver) is a simple assertion that an exception is thrown when a certain case is met. This should be simple right?

My actual test case looks like this in jsTestDriver (having removed any underlying basic code and simply raised the exception in the unit test function itself):

GridControllerTest.prototype.testBasicExceptionType = function () {

assertException(function() {
    throw "InvalidDataSourceException";
}, "InvalidDataSourceException");

};

Which is a test case that asserts that my function throws an exception "InvalidDataSourceException" doesn't it? Initially I tried this with a function that declared the type:

function InvalidDataSourceException (){}

GridControllerTest.prototype.testBasicExceptionType = function () {

assertException(function() {
    throw new InvalidDataSourceException();
}, "InvalidDataSourceException");

};

Can anyone point out the blindingly obvious to me and tell me why I can't get such a simple test to pass? Am I misundertanding the structure of the unit test function?

The difference is that in the first example you're throwing a string and in the second you're throwing an object. Objects in JavaScript don't have canonical names associated with them, essentially because there's no type system (just prototypes). In the second example, the function is assigned to window.InvalidDataSourceException, but the function object as such doesn't have the name in it. In particular, there's no default reflection to get a name or equivalent of toString() to get a canonical value.

Personally, I ditched using assertException entirely, because it was just too flaky for this kind of reason. I started using try-catch blocks. I put a call to fail() at the end of the try block, because it was expect to throw by then, and I put another test point in the catch block, to ensure that the exception was as-expected. It's a better test pattern, in my opinion, since it splits the test for change of control from the test for the reason that control changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM