2014-06-10 93 views
2

我正在评估摩卡,但我不能解决一些基本问题,我写了一个示例测试,我想用node.js和浏览器使用html文件运行它,但是我无法找到一种方法来编写只适用于两种测试的测试,如果我在测试文件中添加了require(s),那么对于node.js而言,我会在浏览器中看到“Uncaught ReferenceError:require is not defined”删除要求(S)我得到的“柴没有定义”节点JS摩卡测试客户端和服务器端

这是代码

(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

检查,如果出口在测试文件中定义做了工作

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

后,我可以简单地做

VAR牛=新牛();