在测试使用qunit显示一个方法的方法时,避免/捕获/验证Javascript警报

Sol*_*dad 7 javascript alert qunit jsunit

我刚开始使用Qunit,想知道是否有办法捕获/验证/省略警报,例如:

function to_test() {
   alert("I'm displaying an alert");
   return 42;
 }
Run Code Online (Sandbox Code Playgroud)

然后有类似的东西:

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
});
Run Code Online (Sandbox Code Playgroud)

我对使用其他单元测试工具的建议持开放态度.

提前致谢!

mem*_*ech 10

好吧,看起来像Sinon.JS就是你要找的.我以前从未使用它,但我确实回答了你的问题.

您可以使用临时函数替换全局函数警报(实际上是window.alert),该函数将记录将显示的消息.

在javascript中很容易做到(window.alert = function(msg) { savedMsg = msg; }).所以你可以在你的测试中做到这一点.

复杂性来自于您在运行测试后进行清理.这就是你需要Sinon.JS与QUnit整合.你需要这个集成脚本.

<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>
Run Code Online (Sandbox Code Playgroud)

  • 来自sinonjs.org的FYI Christian建议删除这种保护不是一个好主意,而是你可以在你的单元测试中使用`window.alert = sinon.spy()`(我还没试过).你必须使用`var _savedAlert = window.alert; try {window.alert = sinon.spy(); } finally {window.alert = _savedAlert; 确保在测试结束时始终恢复window.alert. (5认同)