为什么浏览器中的 mocha 会抛出从 URL 检测到的全局泄漏,而不是从 UNC 路径检测到的全局泄漏



我正在创建一个JavaScript库,想使用BDD,所以我正在尝试摩卡,但我无法让它工作。我希望在客户端上使用该库,因此我假设让它从可浏览的 url 运行是有意义的,在 Web 连接的上下文中,而不仅仅是来自 unc 路径的沙箱。

这是虚拟的起点文件test/test.foobar.js

var assert = chai.assert;
var foobar = {
  sayHello: function() {
    return 'Hello World!';
  }
};
describe('Foobar', function() {
  describe('#sayHello()', function() {
      it('should work with assert', function() {
      assert.equal(foobar.sayHello(), 'Hello World!');
    });
  });
});

这是触发测试的 HTML 页面,测试.html

<html>
<head>
  <meta charset="utf-8">
  <title>Mocha Tests</title>
  <link rel="stylesheet" href="testing/mocha.css" />
  <script src="testing/jquery.js"></script>
  <script src="testing/mocha.js"></script>
  <script>mocha.setup('bdd')</script>
  <script src="testing/chai.js"></script>
  <script src="test/test.foobar.js"></script>
  <script> $(function() { mocha.run(); }) </script>
</head>
<body>
  <div id="mocha"></div>
</body>
</html>

当我在 Chrome 或 Safari 浏览器中打开时

file:///Users/me/dev/sandbox/test.html

它按预期工作,测试通过没有错误

当我在 Chrome 或 Safari 浏览器中打开时

http://localhost/sandbox/test.html

我收到以下错误,测试失败

Error: global leak detected: script1339700707078
    at Runner.checkGlobals (http://localhost/sandbox/testing/mocha.js:3139:21)
    at Runner.<anonymous> (http://localhost/sandbox/testing/mocha.js:3054:44)
    at Runner.emit (http://localhost/sandbox/testing/mocha.js:235:20)
    at http://localhost/sandbox/testing/mocha.js:3360:14
    at Test.run (http://localhost/sandbox/testing/mocha.js:3003:5)
    at Runner.runTest (http://localhost/sandbox/testing/mocha.js:3305:10)
    at http://localhost/sandbox/testing/mocha.js:3349:12
    at next (http://localhost/sandbox/testing/mocha.js:3233:14)
    at http://localhost/sandbox/testing/mocha.js:3242:7
    at next (http://localhost/sandbox/testing/mocha.js:3192:23)

有人可以解释,更好的解决方案吗?

这是将 jQuery 与 mocha 一起使用时遇到的一个问题。 jQuery创建具有唯一id的全局变量... 在您的情况下script133... .最近在摩卡 1.2 中发布,您可以设置通配符忽略...

$(function(){
  mocha
    .globals([ 'script*' ]) // acceptable globals
    .run();
});

确保您是最新的,并进行了适当的配置。

参考:摩卡 1.2.0 发布通知

我找到了解决野生动物园问题的解决方案......取代

<script> $(function() { mocha.run(); }) </script>

<script>
      onload = function(){
        var runner = mocha.run();
      };
</script>

。但仍然在铬中得到错误:-(

最新更新