Coffeescript, nodeunit and global variables

1.1k views Asked by At

I have a web app written in Coffeescript that I'm testing with nodeunit, and I can't seem to get access to global variables ("session" vars in the app) set in the test:

src/test.coffee

root = exports ? this

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

test/test.coffee

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

Results in output:

test.coffee
undefined
✖ test

AssertionError: undefined == 'test'

How do I access globals across tests?

2

There are 2 answers

7
Peter Lyons On

You can share global state using the "global" object.

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"

Load each one from a third module (an interactive session in this example)

$ 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
Todd Chambery On

Create fake window exported global for node:

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

Not very elegant, but it works.