Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..."

like image 561
Ron Philly Avatar asked May 17 '26 10:05

Ron Philly


1 Answers

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.

like image 143
Ned Batchelder Avatar answered May 19 '26 00:05

Ned Batchelder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!