mocha测试客户端和服务器端

时间:2014-06-10 13:09:06

标签: javascript testing mocha chai

我正在评估摩卡,但我无法解决一些基本问题,我写了一个示例测试,我想用node.js和使用html文件的浏览器运行它,但我找不到办法只编写一个适用于两者的测试,如果我在测试文件中添加require,s对node.js没问题,我在浏览器中得到“Uncaught ReferenceError:require is not defined”,删除require(s)我在节点js

中得到“chai未定义”

这是代码

(function(exports) {
  "use strict";

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

})(this);

这是测试

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");
    });


});

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

关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:1)

检查测试文件中是否定义了导出功能

if(typeof(exports) !== "undefined"){
  var Cow = require ("../cow").Cow, 
    chai = require('chai');
}
var
  expect = chai.expect;
之后我就可以做到

var cow = new Cow();

相关问题