angelodiego
angelodiego

Reputation: 245

mocha test client and server side

I'm evaluating mocha but I cant get around some basic problems, I wrote an example test and I'd like to run it both with node.js and in a browser using an html file but I cannot find a way to write only one test that works for both, if I add the require(s) in the test file it's fine for node.js and I get a "Uncaught ReferenceError: require is not defined" in the browser, deleting the require(s) I get "chai is not defined" in node js

this is the code

(function(exports) {
  "use strict";

  function Cow(name) {
    this.name = name || "Anon cow";
  }
  exports.Cow = Cow;

})(this);

this is the test

var chai = require('chai'),
cowobj = require ("../cow"), 
 expect = chai.expect;

describe("Cow", function() {
  describe("constructor", function() {
    it("should have a default name", function() {
      var cow = new cowobj.Cow();
      expect(cow.name).to.equal("Anon cow");
    });


});

this is the html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Cow tests</title>
  <link rel="stylesheet" media="all" href="node_modules/mocha/mocha.css">
</head>
<body>
  <div id="mocha"><p><a href=".">Index</a></p></div>
  <div id="messages"></div>
  <div id="fixtures"></div>
  <script src="node_modules/mocha/mocha.js"></script>
  <script src="node_modules/chai/chai.js"></script>
  <script src="cow.js"></script>
  <script>mocha.setup('bdd')</script>
  <script src="./test/cow_test.js"></script>
  <script>mocha.run();</script>
</body>
</html>

any Idea on how to fix that?

Upvotes: 2

Views: 1290

Answers (1)

angelodiego
angelodiego

Reputation: 245

checking if exports is defined in the test file did the job

if(typeof(exports) !== "undefined"){
  var Cow = require ("../cow").Cow, 
    chai = require('chai');
}
var
  expect = chai.expect;

after that I can simply do

var cow = new Cow();

Upvotes: 1

Related Questions