首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Coffeescript、nodeunit和全局变量

Coffeescript、nodeunit和全局变量
EN

Stack Overflow用户
提问于 2012-01-15 22:59:08
回答 2查看 1.1K关注 0票数 0

我有一个用Coffeescript编写的web应用程序,我正在使用nodeunit进行测试,但我似乎无法访问在测试中设置的全局变量(应用程序中的“session”变量):

src/test.cafee

代码语言:javascript
复制
root = exports ? this

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

test/test.cafee

代码语言:javascript
复制
exports["test"] = (test) ->
    exports.export = "test"
    test.equal test_file.test_exports(), "test"
    test.done()

输出结果:

代码语言:javascript
复制
test.coffee
undefined
✖ test

AssertionError: undefined == 'test'

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

EN

回答 2

Stack Overflow用户

发布于 2012-01-16 20:48:51

为节点创建导出的伪window全局:

src/window.cafee

代码语言:javascript
复制
exports["window"] = {}

src/test.cafee

代码语言:javascript
复制
if typeof(exports) == "object"
    window = require('../web/window')

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

test/test.cafee

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2012-01-16 02:40:41

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

one.coffee:

代码语言:javascript
复制
console.log "At the top of one.coffee, global.one is", global.one
global.one = "set by one.coffee"

two.coffee:

代码语言:javascript
复制
console.log "At the top of two.coffee, global.one is", global.one
global.two = "set by two.coffee"

从第三个模块加载每个模块(本例中为交互式会话)

代码语言:javascript
复制
$ 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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8870634

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档