2015-04-06 78 views
1

所以我试图用jsdom建立一个摩卡测试,经过多次尝试调试后,我将问题缩小到jsdom执行绝对URL脚本(例如http://code.jquery.com/jquery-2.1.3.min.js)而不是相对URL脚本(例如js/script.js )。JSDom没有加载相关脚本

我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

热媒:

<!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; 

回答

2

在您拨打jsdom.env时,请删除html并使用file。我测试过用jsdom 3.1.2代码的这种修改,它的工作原理:(你还需要添加var path = require("path")与其他require呼叫)

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

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

+0

很酷知道,谢谢。 – Alex

+0

有机会尝试它,它没有path.join工作,因为test.js在它自己的文件夹中(所以它试图在与root相对的测试文件夹中找到index.htm)。 – Alex

1

由于3.0的url参数现在被设置为about:默认为空白,而不是implcitly设置为当前目录。一旦我加入url: __dirname,测试结果显示绿色。

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目前不兼容。

+0

另请注意,从v10开始,jsdom有一个新的api,但它仍然支持旧的api,因此为了使用旧的语法,您需要将它包含为: 'var jsdom = require(“jsdom /lib/old-api.js“);'(参见[Github中的解释](https://github.com/tmpvar/jsdom/blob/master/lib/old-api.md)) –