7

Qunit を使い始めたばかりで、アラートをキャプチャ/検証/除外する方法があるかどうかを知りたいです。次に例を示します。

function to_test() {
   alert("I'm displaying an alert");
   return 42;
 }

そして、次のようなものがあります:

test("to_test", function() {
  //in this case I'd like to test the alert.
  alerts("I'm displaying an alert", to_test(), "to_test() should display an alert"); 
  equals(42, to_test(), "to_test() should return 42" );  // in this case I'd like to omit the alert
});

別の単体テスト ツールを使用するという提案も受け入れます。

前もって感謝します!

4

1 に答える 1

10

了解しました。Sinon.JSが探しているもののようです。私はこれまで使ったことがありませんが、あなたの質問に答えるために使いました。

グローバル関数アラート(実際にはwindow.alert)を、表示されたはずのメッセージを記録する一時関数に置き換えることができます。

javascriptで行うのは簡単(window.alert = function(msg) { savedMsg = msg; })です。だからあなたはあなたのテストの中でそれをすることができます。

複雑さは、テストを実行した後のクリーンアップからのみ発生します。そこで、QUnitと統合できるSinon.JSが必要です。この統合スクリプトが必要になります。

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://code.jquery.com/qunit/git/qunit.js"></script>
<script type="text/javascript" src="sinon-1.1.1.js"></script>
<script type="text/javascript" src="sinon-qunit-0.8.0.js"></script>

<script>

    function to_test() {
      window.alert("I'm displaying an alert");
      return 42;
    }

    $(document).ready(function(){

      module("Module A");

      test("first skip alert test ", function() {

      var stub = this.stub(window, "alert", function(msg) { return false; } );

      equals(42, to_test(), "to_test() should return 42" );  
      equals(1, stub.callCount, "to_test() should have invoked alert one time");
      equals("I'm displaying an alert",stub.getCall(0).args[0], "to_test() should have displayed an alert" ); 

    });

  });
</script>

</head>
<body>
  <h1 id="qunit-header">QUnit example</h1>
 <h2 id="qunit-banner"></h2>
 <div id="qunit-testrunner-toolbar"></div>
 <h2 id="qunit-userAgent"></h2>
 <ol id="qunit-tests"></ol>
 <div id="qunit-fixture">test markup, will be hidden</div>
</body>
</html>
于 2011-07-07T10:09:18.593 に答える