2012-01-15 61 views
0

我有一個用Coffeescript編寫的web應用程序,我使用nodeunit進行測試,而且我似乎無法訪問測試中設置的全局變量(應用程序中的「會話」變量) :Coffeescript,nodeunit和全局變量

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 2012-01-15 15:01:44

+0

我的源代碼是用以下標誌編譯的:'nice -n 19 coffee -o web/-b -c -w src /',我將-b添加到Trevor Burnham的連續Cakefile build =(watch,callback) - > \t如果typeof運算手錶是 '功能' \t \t回調=觀看 \t \t手錶=假 \t選項= [ '-b', '-c', '-o', 'LIB', 'SRC'] \t選項。如果手錶 但沒有骰子,則'快速移動'-w'。 – 2012-01-15 15:20:01

+0

嘗試不使用全局變量? – Raynos 2012-01-16 12:52:29

回答

0

您可以使用「全局」對象共享全局狀態。

one.coffee:

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

two.coffee:

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

負載每一個從第三模塊(在該示例的交互式會話)

$ 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

我修正了使用「root」而不是「this」的示例代碼(如果那是你指的特定的)。仍然沒有愛。基本上,我假設如果我在測試中附加一個var到'exports',我應該可以從'exports'在同一個節點vm中的任何文件中訪問它。 – 2012-01-15 20:00:56

+0

是的,但沒有神奇的「導出」變量。這是未定義的,因爲您尚未定義它。根與這沒有關係。 – 2012-01-15 21:34:08

+0

你是對的,「出口」沒有魔法,但「富」,「酒吧」,「猴子」,或「獵豹」都沒有。簡而言之:如何在節點中的文件之間共享數據? – 2012-01-15 22:47:11

1

創建假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() 

不是很優雅,但它的工作原理。