When writing robust JavaScript code, you will probably want to throw exceptions to let programmers know when they’ve misused your API. Sure, you could throw an instance of the built-in Error object, but then during unit testing how will you tell if the exception you’re seeing is yours and not coming from somewhere else?
The solution is to use a custom exception in your method, but this opens up a whole new can of worms. JavaScript’s weak typing and poor support for sub-classing Error mean that a custom exception class can easily be created with no error message, or even worse with no stack trace!
Today, I’m going to help you solve both these problems, and introduce you to a neat feature in QUnit that will help you unit test your methods.
Ok, let’s say you’ve written the following method for your class MyClass:
/**
* Does something interesting
*
* @param input {String} instructions
*/
method: function(input) {
if ((typeof input) === "string") {
// method implementation
}
throw new namespace.InvalidInputError("Input must be a string");
}
/**
* Raise this error whenever a method receives invalid input
*/
namespace.InvalidInputError = function(message) {
var error = new Error(message);
error.name = 'namespace.InvalidInputError';
throw error;
};
test("method: non-string input throws InvalidInputError", function() {
throws(
function() {
this.myClass.method(5);
},
function(error) {
return error.name === "namespace.InvalidInputError";
}
);
});
That’s it! You now know how to unit test exception handling in JavaScript. Please see the included JavaScript demo file for a working example. I hope that you found this helpful and look forward to hearing your feedback.
This blog post is part of a series, like the following blog post to stay tuned and get updates about more topics around software engineering with SAPUI5 and JavaScript:
http://scn.sap.com/community/developer-center/front-end/blog/2013/12/12/engineering-in-javascript
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
4 | |
3 | |
3 | |
2 | |
2 | |
2 | |
1 | |
1 | |
1 | |
1 |