0

我最近一直在切换到 Coffeescript,我认为这是向前迈出的一步(并非总是如你所见)。我遇到的问题是咖啡脚本类:

class @ComparisonCollection extends Backbone.Collection

被编译成

(function() {
  var ComparisonCollection, _ref,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  ComparisonCollection = (function(_super) {
    __extends(ComparisonCollection, _super);

    function ComparisonCollection() {
      _ref = ComparisonCollection.__super__.constructor.apply(this, arguments);
      return _ref;
    }

    return ComparisonCollection;

  })(Backbone.Collection);

}).call(this);

这意味着,除非我像这样在全局命名空间中定义整个类(注意 @ ),否则 Jasmine 无法对其进行测试:

class @ComparisonCollection extends Backbone.Collection

这会将对象 ComparissonCollection 附加到窗口对象(全局命名空间),其中:

  1. 似乎一开始就违背了咖啡脚本的封装
  2. 是一种使我的代码能够对其进行测试的解决方案

你有没有更好的建议如何在不把所有东西都变成window.something

4

1 回答 1

0

一种流行的方法是使用浏览器的打包解决方案。我喜欢简单的法。其他流行的替代品包括 RequireJS、Browserify 和 Ender。

这需要以某种方式打包您的模块。例如,在stitch 和Browserify 中,这与在node 中完全一样(RequireJS 使用AMD 模块,它们略有不同)。

例子:

// collections/comparison.coffee
class ComparisonCollection extends Backbone.Collection

module.exports = ComparisonCollection

使用它(在您自己的应用程序以及 jasmine 测试中):

ComparisonCollection = require 'collections/comparison'

交替:

// collections.coffee
class exports.ComparisonCollection extends Backbone.Collection

使用它:

{ComparisonCollection} = require 'collections'

这也增加了使用jasmine-node进行无头测试的可能性,因此除了在浏览器中测试之外,您还可以在构建时在构建服务器等上轻松测试所有内容。

于 2013-09-12T10:45:40.833 回答