by shigemk2

当面は技術的なことしか書かない

JavaScript Ninjaの極意 2 テストとデバッグの装備

非同期テストの例

<html>
  <head>
    <title>Test Suite</title>
    <script>
      (function() {
        var queue = [], paused = false, results;
        this.test = function(name, fn) {
          queue.push(function() {
            results = document.getElementById("results");
            results = assert(true, name).appendChild(
                document.createElement("ul"));
            fn();
          });
          runTest();
        };
        this.pause = function() {
          paused = true;
        };
        this.resume = function() {
          paused = false;
          setTimeout(runTest, 1);
        };
        function runTest() {
          if (!paused && queue.length) {
            (queue.shift())();
            if (!paused) {
              resume();
            }
          }
        }

        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;
        };
      })();
      window.onload = function() {
        test("非同期テスト #1", function() {
          pause();
          setTimeout(function() {
            assert(true, "第1テスト完了");
            resume();
          }, 1000);
        });
        test("非同期テスト #2", function() {
          pause();
          setTimeout(function() {
            assert(true, "第2テスト完了");
            resume();
          }, 1000);
        });
      };
    </script>
    <style>
      #results li.pass {
        color: green;
      }

      #results li.fail {
        color: red;
      }
    </style>
  </head>
  <body>
    <ul id="results"></ul>
  </body>
</html>
  1. 同じ非同期処理に依存するアサート群を、1個のテストグループに統合する
  2. それぞれのテストグループは、実行キューに入れて、それまでのテストグループがすべて実行を終了した後で実行されるようにする

test→pause→resume