Assert Function In JavaScript

时间:2016-10-20 18:49:47

标签: javascript assert

I was given an exercise but I am not completely understanding the assert function that was given to me. So check this out..

function assert(input, expectedResult, descriptionOfCorrectResult) {
   if (!expectedResult) {
      console.log(descriptionOfCorrectResult);
   } else {
      console.log('test passed');
   }
};

So ! gives us a boolean. So if (!expectedResult) should gives us a true or false. Let's use a simple function for example:

function square(x) {
  return x * x;
};

How would I use the assert function on this simple square function? Can that be done?

1 个答案:

答案 0 :(得分:0)

Let's say you want to test square(4). The first parameter* of assert contains the input you pass to square, the second is your actual test, and the third is when you explain what you're doing. So, you have:

assert(4, square(4) == 16, "The result of square(4) should be its square, 16.");

If it works it logs "test passed"; otherwise it gives you the error message, "The result of square(4) should be its square, 16.".

That's how to use it.

*Actually, since assert doesn't use the first parameter, what you put there really doesn't matter; the log output would be the same if you passed in the Gettysburg Address.

I have one other observation: if the assertion fails, the log doesn't include square's output, it only tells you what the output should be. You probably want to know both. I'd lobby to change this function if I were you.