Skip to content Skip to sidebar Skip to footer

Avoid / Capture / Verify A Javascript Alert When Testing A Method That Displays One With Qunit

I'm just starting using Qunit and would like to know whether is there a way to capture/verify/omit alerts, For example: function to_test() { alert('I'm displaying an alert');

Solution 1:

Alright, looks like Sinon.JS is what you are looking for. I've never used it before, but I did to answer your question.

You can replace the global function alert (which is actually window.alert) with a temporary function that will record the message that would have been displayed.

It's easy to do in javascript (window.alert = function(msg) { savedMsg = msg; }). So you could do that within your test.

The complexity comes only from cleaning up after you've run your test. That's where you need Sinon.JS which can integrate with QUnit. You'll need this integration script.

<html><head><scriptsrc="http://code.jquery.com/jquery-latest.js"></script><linkhref="http://code.jquery.com/qunit/git/qunit.css"type="text/css"media="screen" /><scripttype="text/javascript"src="http://code.jquery.com/qunit/git/qunit.js"></script><scripttype="text/javascript"src="sinon-1.1.1.js"></script><scripttype="text/javascript"src="sinon-qunit-0.8.0.js"></script><script>functionto_test() {
      window.alert("I'm displaying an alert");
      return42;
    }

    $(document).ready(function(){

      module("Module A");

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

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

      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><h1id="qunit-header">QUnit example</h1><h2id="qunit-banner"></h2><divid="qunit-testrunner-toolbar"></div><h2id="qunit-userAgent"></h2><olid="qunit-tests"></ol><divid="qunit-fixture">test markup, will be hidden</div></body></html>

Post a Comment for "Avoid / Capture / Verify A Javascript Alert When Testing A Method That Displays One With Qunit"