Reputation: 53
I'm trying to get a simple test going with QUnit but for some reason it won't locate my function. Am I doing something fundamentally wrong???
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..."
Upvotes: 2
Views: 7383
Reputation: 30520
mytest()
is declared inside the ready()
function, and hence has function scope. It is therefore is inaccessible from outside the ready
function. Your test assumes it has global scope.
Variables and functions declared in block scope are 'hoisted' to the top of the nearest function scope, or to global scope if not declared within a function.
EDIT
Ultimately, I would say the code is structured incorrectly. The ready function is for running things that only need to be run when the document is ready.
Think in terms of a more strongly typed language. Would you scope a function in a Page.Load()
or Window.Load()
or Application.Init()
. No, you would declare it at class level and access it like that.
Think of your JavaScript code in this way. If you want to reduce its scope, declare it within another class.
Upvotes: 3