why mocha in browser throw global leak detected fr

2019-03-19 19:09发布

I'm creating a javascript library and want to use BDD, so I'm giving a try at mocha and I can't make it work. I want that library to be used on the client, so I'm assuming that it make sense to have it running from a browsable url, to be in a context of web connection, and not just a sandbox from a unc path.

here is the dummy starting point file 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!');
    });

  });
});

and here is the html page that trigger the test, 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>

when I open in chrome or safari

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

it works as expected, test pass with no error

when I open in chrome or safari

http://localhost/sandbox/test.html

I get the following error and the test fail

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)

can someone have an explanation, and better a solution?

2条回答
欢心
2楼-- · 2019-03-19 19:43

This was an issue with using jQuery with mocha. jQuery creates global variables that have a unique id... in your case script133.... Recently released in mocha 1.2 you can set up wildcard ignores...

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

Make sure you are up to date, and configure appropriately.

Reference: Mocha 1.2.0 launch notice

查看更多
劳资没心,怎么记你
3楼-- · 2019-03-19 19:54

I found a solution that fixes the issue in safari... replacing

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

by

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

...but still get the error in chrome :-(

查看更多
登录 后发表回答