开发者

How do you test functions defined within $(document).ready()

I'm trying to get a simple test going with QUnit but it won't locate functions defined within $(document).ready().

test.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title></title>
  <script type="text/javascript" src="qunit-git.js"></script>
  <script type="text/javascript" src=开发者_开发问答"jquery.min.js"></script>
  <script type="text/javascript" src="code.js"></script>
  <script type="text/javascript" src="test.js"></script>
  <link rel="stylesheet" type="text/css" href="qunit-git.css" media="screen"/>
</head>
<body>
<h1 id="qunit-header">QUnit Test Suite</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
</body>
</html>

test.js

test('Blah blah', function() {
  ok(mytest(), 'foo bar'
  );
});

code.js

$(document).ready(function() {
  var mytest = function() {
    return true;
  }
});

--> "Died on test #1: mytest is not defined..."


As you start testing, you may find that you need to improve the structure of your code. Defining functions as local variables inside $(document).ready is strange, and makes it so they cannot be accessed anywhere but in the .ready call. Move that function somewhere else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜