如何让node.js和Mocha在浏览器中运行(testing)?

在Win10.64中,我正在命令行运行testing,结果如下:

>mocha test Array #indexOf() √ should return -1 when the value is not present 1 passing (16ms) 

但是在Chrome中,控制台错误是: 未捕获的ReferenceError:require没有被定义(匿名函数)@test.lead-helper.js:1

test.lead-helper.js:

 var assert = require("assert"); describe('Array', function() { describe('#indexOf()', function () { it('should return -1 when the value is not present', function () { assert.equal(-1, [1,2,3].indexOf(5)); assert.equal(-1, [1,2,3].indexOf(0)); }); }); }); 

和HTMLtesting运行者:

 <html> <head> <meta charset="utf-8"> <title>Mocha Tests</title> <link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" /> </head> <body> <div id="mocha"></div> <div id="messages"></div> <div id="fixtures"></div> <script src="https://cdn.rawgit.com/jquery/jquery/2.1.4/dist/jquery.min.js"></script> <script src="https://cdn.rawgit.com/Automattic/expect.js/0.3.1/index.js"></script> <script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.3.0/chai.js"></script> <script src="lead-helper.js"></script> <script>mocha.setup('bdd')</script> <script src="test/test.lead-helper.js"></script> <script> mocha.checkLeaks(); mocha.globals(['jQuery']); mocha.run(); </script> </body> </html> 

你的代码似乎在交叉工作。 你加载柴:

  <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.3.0/chai.js"></script> 

这是一个function齐全的断言库,但是接下来使用require("assert") ,这似乎是尝试将Node的assert库加载到浏览器中。 可能有一种方法可以通过使用Browserify来加载,但是我不明白为什么要这么做,因为您已经加载Chai,而且没有任何迹象表明其他代码需要Browserify。

我只是删除require呼叫,而是有:

 var assert = chai.assert; 

发生这种情况是因为默认情况下,浏览器环境中没有require()方法,所以您必须对脚本模块进行一些更改。 有几种方法可以去:

  • 使用其他方法加载脚本,例如使用帮助<script>标记。
  • 使用CommonJS实现,如Browserify或Component 。
  • 使用像RequireJs这样的AMD实现。