Reputation: 2269
So I'm trying to set up a mocha test with jsdom and after many attempts at debugging I narrowed down the problem to jsdom executing absolute URL scripts (e.g. http://code.jquery.com/jquery-2.1.3.min.js
) but not relative URL scripts (e.g. js/script.js
).
My test.js is below:
var assert = require("assert");
var fs = require('fs');
var jsdom = require("jsdom");
describe('Foo Test', function(){
it('Foo Check', function(done){
this.timeout(5000);
jsdom.env({
html: fs.readFileSync('index.htm')
,features: {
FetchExternalResources: ["script"]
,ProcessExternalResources: ["script"]
}
,done: function(errors, window){
if(errors != null) console.log('Errors', errors);
var $ = window.$; // $ is defined
var foo = window.foo; //foo is undefined
assert(foo);
done();
}
});
});
});
And the error:
Uncaught AssertionError: undefined == true
The htm:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Foo</title>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
</body>
</html>
script.js:
var foo = true;
Upvotes: 2
Views: 1786
Reputation: 151511
In your call to jsdom.env
, remove html
and use file
. I've tested this modification of your code with jsdom 3.1.2, and it works:
jsdom.env({
file: path.join(__dirname, "index.htm")
,features: {
[... etc ...]
(You also need to add var path = require("path")
with your other require
calls.)
The problem with using html
is that then jsdom has no idea what the base URL of the HTML is. If you use file
, it will load the code from the path you give and use the path as the base URL.
Upvotes: 2
Reputation: 2269
As of 3.0 the url parameter is now set to about:blank by default instead of implcitly set to current dir. Once I added url: __dirname
the test came up green isntantly.
var assert = require("assert");
var fs = require('fs');
var jsdom = require("jsdom");
describe('Foo Test', function(){
it('Foo Check', function(done){
this.timeout(5000);
jsdom.env({
html: fs.readFileSync('index.htm')
,url: __dirname
,features: {
FetchExternalResources: ["script"]
,ProcessExternalResources: ["script"]
}
,done: function(errors, window){
if(errors != null) console.log('Errors', errors);
var $ = window.$; // $ is defined
var foo = window.foo; //foo is undefined
assert(foo);
done();
}
});
});
});
Also I want to mention that jQuery 2.x does not seem compatible currently with jsdom.
Upvotes: 1