【问题标题】:Writing tests in Mocha/Chai with the namespace module paradigm使用命名空间模块范式在 Mocha/Chai 中编写测试
【发布时间】:2012-05-12 16:26:50
【问题描述】:

我正在编写一系列用于进行数学运算的咖啡脚本文件,我需要编写一些测试。我认为摩卡和柴是要走的路。目前,我使用命名空间方法将所有单独的函数组合在一起以保持整洁:

namespace = (target, name, block) ->
  [target, name, block] = [(if typeof exports isnt 'undefined' then exports else window), arguments...] if arguments.length < 3
  top    = target
  target = target[item] or= {} for item in name.split '.'
  block target, top

exports? exports.namespace = namespace

我现在想测试的是我的矩阵类,它看起来有点像这样:

namespace "CoffeeMath", (exports) ->

  class exports.Matrix4
    for name in ['add', 'subtract', 'multiply', 'divide', 'addScalar', 'subtractScalar', 'multiplyScalar', 'divideScalar', 'translate']
        do (name) ->
          Matrix4[name] = (a,b) ->
          a.copy()[name](b)

    Matrix4.DIM = 4

    # Take a list in column major format
    constructor: (@a=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]) ->
      # etc etc ...

现在用可爱的coffeescript编译器编译所有这些都很好。我有一个这样的测试:

chai = require 'chai'
chai.should()

{namespace} = require '../src/aname'
{Matrix4} = require '../src/math'

describe 'Matrix4 tests', ->
  m = null
  it 'should be the identity matrix', ->
    m  = new exports.Matrix4()
    m.a.should.equal '[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]'

问题是,我收到以下错误:

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
ReferenceError: namespace is not defined
    at Object.<anonymous> (/Users/oni/Projects/Saito.js/src/math.coffee:3:3)
    at Object.<anonymous> (/Users/oni/Projects/Saito.js/src/math.coffee:631:4)
    at Module._compile (module.js:441:26)

aname 我相信应该包括在内,并且导出命名空间函数,所以我看不出为什么没有定义命名空间。有什么想法吗?

【问题讨论】:

    标签: node.js coffeescript mocha.js


    【解决方案1】:

    来自fine manual

    要导出对象,请添加到特殊的exports 对象。

    然后,exports is returned by require:

    module.exports 是作为require 调用的结果实际返回的对象。

    所以,当你这样说时:

    namespace = require '../src/aname'
    

    您的测试中有 namespace.namespace 可用。

    CoffeeScript 将每个文件包装在 function wrapper 中以避免污染全局命名空间:

    所有 CoffeeScript 输出都包装在一个匿名函数中:(function(){ ... })(); 这个安全包装器与自动生成的 var 关键字相结合,使得意外污染全局命名空间变得非常困难。

    这意味着你在编译好的 JavaScript 中有这样的东西:

    (function() {
        exports.namespace = ...
    })();
    (function() {
        # Matrix4 definition which uses the 'namespace' function
    })();
    (function() {
        var namespace = ...
    })();
    

    结果是 namespace 在您定义 Matrix4 的位置不可见,因为 test 和 Matrix4 存在于不同的函数中,因此存在不同的范围。

    如果你想在你的数学文件中使用namespace,那么你必须在那里require它而不是在requires你的数学文件的代码中。

    【讨论】:

    • 谢谢!这是一个很大的帮助。仍在尝试将基于 Web 的咖啡脚本应用程序与基于节点的测试环境合并。这又近了一步。干杯
    猜你喜欢
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多