2017-04-21 54 views
0

我是摩卡新手。當我從terminal運行時,我的腳本在下面工作。但是,當我從testrunner.html運行時沒有結果。在檢查時,這似乎是因爲var xl = require('./excel');。如果我評論這個聲明,它是有效的。我怎樣才能做這項工作?我需要爲我的腳本導入自定義模塊。從TestRunner.html導入模塊需要聲明錯誤

更新test.js納入RequireJS

  • 後的變化:適用於瀏覽器和termial

module1.js

if(typeof define !== 'undefined') 
{ 
    define([], function() { 
     return { 
      get: function() { 
       return get(); 
      } 
     }; 
    }); 
} 
else if(typeof exports !== 'undefined') { 
    module.exports = { 
     get: function(){ 
      return get(); 
     }  
    };  
} 

function get(){ 
    return "hello node world"; 
} 

test.js

if(typeof requirejs == 'undefined') {var requirejs = require('requirejs');} 
if(typeof chai == 'undefined') {var chai = require('chai');} 
requirejs.config({ 
    baseUrl: '.', 
    paths: { 

    }, 
    nodeRequire: require 
}); 

describe("RequireTest()", function(){  
    var module1; 
    before(function(done){ 
     requirejs(['./module1'], 
      function(_module) {      
       console.log('before fired'); 
       module1 = _module; 
       if(typeof requirejs == 'undefined') {mocha.run();} 
       done();    
     }); 
    });   
    it('test case: ', function(){ 
     console.log(module1.get()); 
     chai.expect(1+1).to.equal(2); 
    }); 
}); 

testrunner.html(片斷)

<div id="mocha"></div> 
<script src="../node_modules/mocha/mocha.js"></script> 
<script src="../node_modules/chai/chai.js"></script> 
<script src="../node_modules/requirejs/require.js"></script> 
<script>mocha.setup('bdd')</script> 

<script src="./test.js"></script> 

<script>mocha.run();</script> 

回答

1

當你在你正在使用的Node.js,它提供require從命令行運行摩卡。

當您在瀏覽器中運行它時,瀏覽器不提供require。您需要在運行時使用模塊加載器,如RequireJS或SystemJS。或者您需要使用像Webpack或Browserify這樣的打包程序,它可以事先處理您的代碼,並將其轉換爲包含所有代碼的單個包。

請注意,無論您使用的第三方模塊是否可以在瀏覽器中加載,都需要逐個模塊進行確定。例如,如果使用使用Node child_process模塊生成新進程的模塊,則無法在瀏覽器中使用該模塊,因爲瀏覽器不提供child_process

+0

謝謝。根據我對readup的理解,我更新了原來的問題以使用'RequireJS'。而且,我仍然試圖讓它在瀏覽器上運行。請指教。 –

+0

hello @Louis,我只是更新了原來的test.js以使用'RequireJS'。它從終端運行。但是,不通過瀏覽器。缺失的缺口是什麼?提前致謝。 –

+0

您在瀏覽器中遇到什麼錯誤?記得在我的回答中,我提到一些節點模塊不會在瀏覽器中運行。這可能是你的問題。回想你的另一個問題,在我看來,你想從文件系統讀取。您不能在瀏覽器中執行此操作(在列表中不是從Node到瀏覽器代碼的直接轉換:瀏覽器不提供['fs'](https://nodejs.org/api/fs.html))。 – Louis