我有一个用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 :(得分: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()
不是很优雅,但它有效。
答案 1 :(得分: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
{}