【问题标题】:How do you test functions defined within $(document).ready()你如何测试 $(document).ready() 中定义的函数
【发布时间】:2011-06-17 19:56:38
【问题描述】:

我正在尝试使用 QUnit 进行一个简单的测试,但它不会找到 $(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;
  }
});

-->“在测试 #1 中死亡:mytest 未定义...”

【问题讨论】:

  • 为什么你的函数需要在$(document).ready()中定义?
  • mytest 是一个局部变量。你不能从它定义的函数之外访问它。

标签: javascript jquery unit-testing qunit


【解决方案1】:

当您开始测试时,您可能会发现您需要改进代码的结构。将函数定义为 $(document).ready 中的局部变量很奇怪,并且使得它们不能在任何地方访问,只能在 .ready 调用中访问。将该函数移至其他位置。

【讨论】:

    猜你喜欢
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 2010-12-22
    • 2014-04-20
    • 2012-02-17
    • 2017-02-07
    相关资源
    最近更新 更多