Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
413 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

assert(false, "Second test failed");

returns false, which invalidates the whole test.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...