2012-01-15 4 views
0

私はnodenameでテストしているCoffeescriptで書かれたWebアプリケーションを持っており、テストで設定されたグローバル変数(「セッション」変数)にアクセスできないようです:出力のCoffeescript、nodeunit、およびglobal変数

のsrc/test.coffee

root = exports ? this 

this.test_exports = -> 
    console.log root.export 
    root.export 

テスト/ test.coffee

exports["test"] = (test) -> 
    exports.export = "test" 
    test.equal test_file.test_exports(), "test" 
    test.done() 

結果:

test.coffee 
undefined 
✖ test 

AssertionError: undefined == 'test' 

テストでグローバルにアクセスするにはどうすればよいですか?

+0

'b'-Flagでコンパイルしてみてください。これにより、セキュリティクロージャが追加されなくなります。 – TimWolla

+0

ソースが 'nice -n 19 coffee -o web/-b -c -w src /'フラグでコンパイルされました。Trevor Burnhamの連続Cakefileビルド=(watch、callback)に-bを追加しました - > \t typeof演算時計は '関数' \t \tコールバックがある場合= falseを= \t \t時計を見 \tオプション= [ '-b'、 '-c'、 '-o'、 'libに'、 'SRC'] \tオプション を見るなら.unshift '-w'だがダイスはない。 –

+0

グローバル変数を使用しないでください。 – Raynos

答えて

0

"グローバル"オブジェクトを使用してグローバル状態を共有できます。

one.coffee:

console.log "At the top of one.coffee, global.one is", global.one 
global.one = "set by one.coffee" 

two.coffee:第3のモジュール(この例では、対話型セッション)

$ coffee 
coffee> require "./one"; require "./two" 
At the top of one.coffee, global.one is undefined 
At the top of two.coffee, global.one is set by one.coffee 
{} 
+0

"this"の代わりに "root"を使用するようにサンプルコードを修正しました(これが特に参考になっている場合)。まだ愛はありません。基本的には、テストで 'exports'にvarを付けると、同じノードvm内のファイルで' exports'からアクセスできるはずです。 –

+0

ええ、魔法の "エクスポート"変数はありません。あなたが定義していないので、それは未定義です。これは問題ではありません。 –

+0

"エクスポート"には魔法はありませんが、 "foo"、 "bar"、 "monkey"、 "cheetah"のいずれも正しくありません。単純に言えば、ノード内のファイル間でデータをどのように共有するのでしょうか? –

1

から各々は偽を作成

console.log "At the top of two.coffee, global.one is", global.one 
global.two = "set by two.coffee" 

ロードwindowノードのグローバルエクスポート:

のsrc/window.coffee

exports["window"] = {} 

のsrc/test.coffee

if typeof(exports) == "object" 
    window = require('../web/window') 

this.test_exports = -> 
    console.log window.export 
    window.export 

テスト/ test.coffee

test_file = require "../web/test" 
window = require "../web/window'" 

exports["test"] = (test) -> 
    window.export = "test" 
    test.equal test_file.test_exports(), "test" 
    test.done() 

ない非常にエレガントな、それが動作します。

関連する問題