【问题标题】:Better testing of coffeescript with Jasmine用 Jasmine 更好地测试咖啡脚本
【发布时间】:2013-09-16 14:06:43
【问题描述】:

我最近一直在切换到 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

【问题讨论】:

    标签: coffeescript jasmine


    【解决方案1】:

    一种流行的方法是使用浏览器的打包解决方案。我喜欢stitch 的简洁。其他流行的替代品包括 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-08
    • 1970-01-01
    • 2012-01-24
    • 2013-10-30
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    相关资源
    最近更新 更多