WacławJasper
WacławJasper

Reputation: 3384

javascript - an assert function that doesnt require you to enter an error message

Implementing an assert in javascript is not difficult:

assert = function(expression,errorMessage){
    if (!expression){
        errorMessage = errorMessage || "(no msg)";
        throw new Error("assert failed: "+errorMessage);
    }
    return true;
};

However, using this version of assert is tiresome because you have to have a meaningful error message for every test case:

var types = {isNumber:function(x){return typeof x === "number" && isFinite(x)}}

assert(types.isNumber(1)===true,"types.isNumber(1)===true");
assert(types.isNumber(NaN)===false,"types.isNumber(NaN)===false");

My question is that is there a way to implement the assert function such that it only takes one expression and it can return meaningful error message if that expression is not met? Like:

assert(SOMETHING_that_is_not_true); // throw Error: SOMETHINGELSE that refers to this particular assertion
assert(SOMETHING_that_is_not_true2); // throw Error: SOMETHINGELSE2 that refers to this different assertion

Upvotes: 0

Views: 67

Answers (2)

somethinghere
somethinghere

Reputation: 17358

I just want to add this as it will work. But it is

Not advised

As it uses eval, which is, juck. But it is useful if you don't face it to the client. (What am I saying? It is not advised. End of that. But it does work.)

function assert(expression){
    var success = eval(expression);
    if(!success) throw new Error("assert failed: "+ expression);
    else return true;
}

Then you can do

assert("types.isNumber(1)===true");

So te reiterate, use @James Thorpe s code (hopefully) above.

Upvotes: 0

James Thorpe
James Thorpe

Reputation: 32222

It's a bit more code than a simple expression for each assertion, but how about this?

assert = function(expression){
    if (!expression()){
        errorMessage = expression.toString() || "(no msg)";
        throw new Error("assert failed: "+errorMessage);
    }
    return true;
};

assert(function() { return 'b' == 'a' });

Upvotes: 2

Related Questions