2015-04-06 74 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)) –