JSDom不加载相关的脚本

所以我试图用jsdombuild立一个摩卡testing,经过多次debugging,我把问题的范围缩小到jsdom执行绝对URL脚本(例如http://code.jquery.com/jquery-2.1.3.min.js ),但不是相对的URL脚本(例如js/script.js )。

我的test.js如下:

 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(); } }); }); }); 

并且错误: Uncaught AssertionError: undefined == true

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; 

在您对jsdom.env的调用中,删除html并使用file 。 我已经用jsdom 3.1.2testing了你的代码的修改,它可以工作:

  jsdom.env({ file: path.join(__dirname, "index.htm") ,features: { [... etc ...] 

(你还需要添加var path = require("path")和其他require调用。)

使用html的问题是,那么jsdom不知道HTML的基本URL是什么。 如果使用file ,它将从您提供的path加载代码,并使用该path作为基本URL。

从3.0开始,url参数现在默认设置为about:blank,而不是设置为当前的dir。 一旦我添加url: __dirnametesting绿色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(); } }); }); }); 

另外我想提一下,jQuery 2.x似乎与jsdom目前不兼容。