0

我有一个用 Coffeescript 编写的 Web 应用程序,我正在使用 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'

如何跨测试访问全局变量?

4

2 回答 2

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()

不是很优雅,但它有效。

于 2012-01-16T12:48:51.380 回答
0

您可以使用“全局”对象共享全局状态。

一、咖啡:

console.log "At the top of one.coffee, global.one is", global.one
global.one = "set by one.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
{}
于 2012-01-15T18:40:40.790 回答