2014-06-10 92 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牛=新牛();