0

In the following code, from "Secrets of the JavaScript Ninja," why does "Another test." show up in red font?

http://jsfiddle.net/dtHyc/

<html>
  <head>
    <title>Test Suite</title>
    <script>

      (function() {
        var results;
        this.assert = function assert(value, desc) {
          var li = document.createElement("li");
          li.className = value ? "pass" : "fail";
          li.appendChild(document.createTextNode(desc));
          results.appendChild(li);
          if (!value) {
            li.parentNode.parentNode.className = "fail";
          }
          return li;
        };
        this.test = function test(name, fn) {
          results = document.getElementById("results");
          results = assert(true, name).appendChild(
              document.createElement("ul"));
          fn();
        };
      })();

      window.onload = function() {
        test("A test.", function() {
          assert(true, "First assertion completed");
          assert(true, "Second assertion completed");
          assert(true, "Third assertion completed");
        });
        test("Another test.", function() {
          assert(true, "First test completed");
          assert(false, "Second test failed");
          assert(true, "Third assertion completed");
        });
        test("A third test.", function() {
          assert(null, "fail");
          assert(5, "pass")
        });
      };
    </script>
    <style>
      #results li.pass { color: green; }
      #results li.fail { color: red; }
    </style>
  </head>
  <body>
    <ul id="results"></ul>
  </body>
</html>
4
  • Who downvoted this, and why is it not a real question? Commented Feb 3, 2013 at 2:21
  • @JosephSilber I think "too localized" is more appropriate. Commented Feb 3, 2013 at 3:21
  • @GGG - True, so I voted as such. Still not a reason to downvote. Commented Feb 3, 2013 at 3:26
  • 1
    @JosephSilber, wasn't me, although it also doesn't show any original research IMO. Commented Feb 3, 2013 at 23:56

1 Answer 1

5

Since a string is truthy ("Second test failed" != false),

assert(false, "Second test failed");

returns false, which invalidates the whole test.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, Joseph. That's because of if (!value) { li.parentNode.parentNode.className = "fail"; } yea?
@Kevin - Yes. Or, more simply put, because (! value) == true.
as a side question, what does the fn() mean shown in function test()?
@Kevin - That's just the variable that holds the function you pass in as a second argument to test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.