Coffeescript, 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'
Как получить доступ к глобальным переменным во всех тестах?
2 ответа
Создать подделку 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()
Не очень элегантно, но это работает.
Вы можете поделиться глобальным состоянием, используя "глобальный" объект.
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
{}