2012-05-12 11 views
0

数学演算を行うための一連のcoffeescriptファイルを書いているので、いくつかのテストを書く必要があります。私はモカとチャイが行く道だと思っています。現時点では、Imはきちんと物事を保つために一緒にグループにすべての私の別々の機能を名前空間法を用いた:名前空間モジュールのパラダイムでMocha/Chaiでテストを書く

namespace = (target, name, block) -> 
    [target, name, block] = [(if typeof exports isnt 'undefined' then exports else window), arguments...] if arguments.length < 3 
    top = target 
    target = target[item] or= {} for item in name.split '.' 
    block target, top 

exports? exports.namespace = namespace 

私は、現時点ではテストしたい事が少し見えた、私の行列クラスです

namespace "CoffeeMath", (exports) -> 

    class exports.Matrix4 
    for name in ['add', 'subtract', 'multiply', 'divide', 'addScalar', 'subtractScalar', 'multiplyScalar', 'divideScalar', 'translate'] 
     do (name) -> 
      Matrix4[name] = (a,b) -> 
      a.copy()[name](b) 

    Matrix4.DIM = 4 

    # Take a list in column major format 
    constructor: (@a=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]) -> 
     # etc etc ... 

これらのすべてを素敵なcoffeescriptコンパイラでコンパイルすると、すべてうまくいきます。私はこのようなテストを持っている:

chai = require 'chai' 
chai.should() 

{namespace} = require '../src/aname' 
{Matrix4} = require '../src/math' 

describe 'Matrix4 tests', -> 
    m = null 
    it 'should be the identity matrix', -> 
    m = new exports.Matrix4() 
    m.a.should.equal '[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]' 

問題がある、私は次のエラーを取得する:

node.js:201 
     throw e; // process.nextTick error, or 'error' event on first tick 
      ^
ReferenceError: namespace is not defined 
    at Object.<anonymous> (/Users/oni/Projects/Saito.js/src/math.coffee:3:3) 
    at Object.<anonymous> (/Users/oni/Projects/Saito.js/src/math.coffee:631:4) 
    at Module._compile (module.js:441:26) 

ANAMEは、私は信じて含まれるべきと名前空間があるなぜ私が見るカントので、それは名前空間の関数をエクスポート定義されていません。何かご意見は?あなたが言うとき

module.exports is the object that's actually returned as the result of a require call.

だから、この:fine manualから

答えて

1

To export an object, add to the special exports object.

そして、exports is returned by require

namespace = require '../src/aname' 

あなたのテスト内部で利用可能なnamespace.namespace持っています。

のCoffeeScriptは、グローバルな名前空間を汚染を避けるためにfunction wrapper内の各ファイルをラップ:

all CoffeeScript output is wrapped in an anonymous function: (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident.

これは、あなたがコンパイルされたJavaScriptでこのような何かを持っていることを意味します

(function() { 
    exports.namespace = ... 
})(); 
(function() { 
    # Matrix4 definition which uses the 'namespace' function 
})(); 
(function() { 
    var namespace = ... 
})(); 

結果はそのnamespaceですテストの結果Matrix4と定義されていて、Matrix4が別々の関数に存在し、スコープが分離している場合は表示されません。

数値ファイルの中にnamespaceを使用する場合は、数値ファイルrequireの代わりに、requireをコードに追加する必要があります。

+0

ありがとうございます!その大きな助け。まだWebベースのcoffeescriptアプリケーションをノードベースのテスト環境とマージしようとしています。これは一歩近づいています。乾杯 – Oni

関連する問題