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

Alp*_*pha 9 javascript testing mocha.js

我正在创建一个javascript库并且想要使用BDD,所以我试试mocha并且我无法使其工作.我希望在客户端上使用该库,所以我假设从可浏览的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!');
    });

  });
});
Run Code Online (Sandbox Code Playgroud)

这是触发测试的html页面,test.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>
Run Code Online (Sandbox Code Playgroud)

当我打开铬或野生动物园

file:///Users/me/dev/sandbox/test.html
Run Code Online (Sandbox Code Playgroud)

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

当我打开铬或野生动物园

http://localhost/sandbox/test.html
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

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

小智 6

这是使用jQuery与mocha的问题.在您的情况下,jQuery创建具有唯一ID的全局变量script133....最近在mocha 1.2中发布你可以设置通配符忽略...

$(function(){
  mocha
    .globals([ 'script*' ]) // acceptable globals
    .run();
});
Run Code Online (Sandbox Code Playgroud)

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

参考:摩卡1.2.0发布通知


Alp*_*pha 0

我找到了解决 safari 中问题的解决方案...替换

<script> $(function() { mocha.run(); }) </script>
Run Code Online (Sandbox Code Playgroud)

经过

<script>
      onload = function(){
        var runner = mocha.run();
      };
</script>
Run Code Online (Sandbox Code Playgroud)

...但在 chrome 中仍然出现错误:-(

  • 如果您在 onload 上方的脚本标记中添加以下内容,它应该在 chrome 中修复它(全局变量通常也很有用): mocha.setup({ ui: 'bdd', globals: ['script*'] }) (2认同)