3

我有這個gulp任務:測試Chrome擴展 - 要求錯誤

gulp.task('test', function() { 
    return gulp.src('test/runner.html') 
     .pipe(mochaPhantomJS()); 
}); 

這是我runner.html

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Mocha</title> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
     <link rel="stylesheet" href="../node_modules/mocha/mocha.css" /> 
    </head> 
    <body> 
     <script src="../node_modules/mocha/mocha.js"></script> 
     <script>mocha.setup('bdd')</script> 
     <script src="../node_modules/chai/chai.js"></script> 
     <script src="../node_modules/requirejs/require.js"></script> 

     <script> 
      var assert = chai.assert; 
      var expect = chai.expect; 
      var should = chai.should(); 
     </script> 
     <script src="spec/test.js"></script> 
     <script> 
      if (window.mochaPhantomJS) { 
       console.log('Running mochaPhantomJS...'); 
       mochaPhantomJS.run(); 
      } else { 
       console.log('Running mocha...'); 
       mocha.run(); 
      } 
     </script> 
    </body> 
</html> 

這裏是我的test.js文件:

var chrome = require('sinon-chrome'); 
var popup = require('../../source/scripts/popup'); 

describe('sumit', function(){ 
    before(function() { 
     global.chrome = chrome; 
    }); 
    it('Should return 1', function(){ 
     assert(popup.sum(0,1) === 1); 
    }); 
}) 

但是,當我運行gulp test我收到此錯誤消息:

Error: Module name "sinon-chrome" has not been loaded yet for context: _. Use require([])

http://requirejs.org/docs/errors.html#notloaded

in defaultOnError at file:///c:/dev/extensions/NEW_EXPRESS/node_modules/requirejs/require.js:1 in onError at file:///c:/dev/extensions/NEW_EXPRESS/node_modules/requirejs/require.js:547 in localRequire at file:///c:/dev/extensions/NEW_EXPRESS/node_modules/requirejs/require.js:1433 in requirejs at file:///c:/dev/extensions/NEW_EXPRESS/node_modules/requirejs/require.js:1794

+0

請[編輯]這個問題要切合主題:包括** **完全[MCVE]認爲重複問題。包括一個* manifest.json *,一些背景*和*內容腳本。尋求調試幫助的問題(「**爲什麼不是這個代碼工作?」)必須包括:►期望的行爲,►特定問題或錯誤*和*►在問題中重現問題所需的最短代碼**本身**。沒有明確問題陳述的問題對其他讀者無益。請參閱:「**如何創建[mcve] **」,[我可以在此處詢問哪些主題?](http://stackoverflow.com/help/on-topic)和[問]。 – Makyen

+1

錯誤中的鏈接意味着您應該使用異步請求方法。 I.e 'require(['sinon-chrome'],function(chrome){test.js }中的其他所有內容);' 即使執行該更改,您是否仍然收到同樣的錯誤? – dan

回答

1

link in the error message中,這意味着您應該使用異步require方法。

所以,如果你更新test.js以下內容,那麼就應該解決這個問題:

require(['sinon-chrome'], function (chrome) { 
    var popup = require('../../source/scripts/popup'); 

    describe('sumit', function(){ 
     before(function() { 
      global.chrome = chrome; 
     }); 
     it('Should return 1', function(){ 
      assert(popup.sum(0,1) === 1); 
     }); 
    }) 
}); 
+0

或者你可以在'describe()'裏面的'before()'回調中放入'popup = require('../../ source/scripts/popup'';')。 –