2017-08-15 96 views
1

我可以在瀏覽器中異步加載摩卡模塊嗎?我可以肯定地用柴做。是否有任何解決方法使摩卡工作在類似amd的風格中?異步運行mochajs(類AMD)

require.config({ 
    baseUrl: "/scripts", 
    paths: { 
     "mocha": "framework/mocha", 
     "chai": "framework/chai", 
     "first": "custom/first" 
    } 
}); 

require(['first', 'mocha', 'chai'], function (first, mocha, chai) { 
     first.echo(); 

     console.log('something'); 
     console.log('something'); 

     mocha.ui('tdd'); 
     var assert = chai.assert; 

     suite('"Home" Page Tests', function() { 
      test('page should contain link to contact page', function() { 
       assert($('a[href="/contact"]').length); 
      }); 
     }); 

     mocha.run(); 

     console.log('whatever'); 
    }); 
以上 firstchai工作精細的代碼示例中

,而mocha是未定義的。

回答

1

摩卡並不支持AMD,所以如果你打算使用RequireJS加載摩卡,那麼你需要一個shim。下面是一個index.html文件,其中包含一個小例子:

<!DOCTYPE html> 
<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8"/> 
    <link href="node_modules/mocha/mocha.css" type="text/css" media="screen" rel="stylesheet" /> 
    <script type="text/javascript" src="node_modules/requirejs/require.js"></script> 
    </head> 
    <body> 
    <div id="mocha"></div> 
    <script> 
     require.config({ 
      paths: { 
       mocha: 'node_modules/mocha/mocha', 
      }, 
      shim: { 
       mocha: { 
       exports: "mocha", 
       } 
      }, 
     }); 

     require(["mocha"], function (mocha) { 
     mocha.setup("bdd"); 
     it("foo", function() {}); 
     mocha.run(); 
     }); 
    </script> 
    </body> 
</html> 

您需要在index.html位於同一目錄中已運行npm install requirejs mocha

在我希望能夠使用Mocha構造我用這個代替shim情況:

shim: { 
     mocha: { 
      exports: "mocha", 
      init: function() { return {mocha: mocha, Mocha: Mocha }; } 
     } 
    },