Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何获取node.js&;摩卡在浏览器中运行(测试)?_Javascript_Node.js_Testing_Mocha.js - Fatal编程技术网

Javascript 如何获取node.js&;摩卡在浏览器中运行(测试)?

Javascript 如何获取node.js&;摩卡在浏览器中运行(测试)?,javascript,node.js,testing,mocha.js,Javascript,Node.js,Testing,Mocha.js,在Win10.64中,我在命令行上运行测试,并获得预期结果: >mocha test Array #indexOf() √ should return -1 when the value is not present 1 passing (16ms) 但在Chrome中,控制台错误是:uncaughtreferenceerror:require未定义(匿名函数)@test.leadheloper.js:1 test.lead-helper.js: va

在Win10.64中,我在命令行上运行测试,并获得预期结果:

>mocha test
   Array
     #indexOf()
       √ should return -1 when the value is not present
   1 passing (16ms)
但在Chrome中,控制台错误是:uncaughtreferenceerror:require未定义(匿名函数)@test.leadheloper.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));
    });
  });
});
和HTML测试运行程序:

<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>

摩卡咖啡测试
摩卡咖啡设置(“bdd”)
摩卡。检查泄漏();
mocha.globals(['jQuery']);
mocha.run();

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

  • 使用其他方法加载脚本,例如使用帮助
    标签
  • 使用CommonJS实现,如,或
  • 像这样使用AMD实现

您的代码似乎在起交叉作用。您可以下载:

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

谢谢请帮助我理解第一个选项:
标记(似乎最简单);我应该这样添加一个或多个node.js文件吗?我猜您正在使用
require()
方法加载一个被排除在单独文件中的模块。不要这样做,而是尝试使用:
以这种方式加载每个必需的文件。我明白你现在说的了。谢谢你的解释。删除不必要的
require();var assert=chai.assert因此,现在测试将在浏览器和命令行中运行。
var assert = chai.assert;