异步运行mochajs(类似AMD)

时间:2017-08-15 20:32:09

标签: javascript requirejs mocha

我可以在浏览器中异步加载mocha模块吗?我可以肯定地用柴做。是否有任何解决方法可以使mocha以类似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 个答案:

答案 0 :(得分:1)

Mocha不支持AMD,因此如果您要使用RequireJS加载Mocha,则需要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>

您需要在npm install requirejs mocha所在的同一目录中运行index.html

如果我希望能够使用Mocha构造函数,请使用此shim代替:

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