Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get node.js & Mocha to run (test) in browser?

In Win10.64 I'm running the test on the command line with expected results:

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

But in Chrome, console error is: Uncaught ReferenceError: require is not defined(anonymous function) @ 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));
    });
  });
});

and the HTML test runner:

<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>
like image 640
Rob_M Avatar asked Oct 26 '25 19:10

Rob_M


1 Answers

Your code seems to be working at cross-purpose. You load Chai:

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

which is a full-featured assertion library but then you use require("assert") which seems to be an attempt at loading Node's assert library into your browser. There may be a way to get this to load by using Browserify but I don't see why you'd do that, seeing as you already load Chai, and there is no indication that the rest of your code needs Browserify.

I would just remove the require call and instead have:

var assert = chai.assert;
like image 83
Louis Avatar answered Oct 28 '25 10:10

Louis