templates - 使用模板进行 Jasmine 测试

标签 templates backbone.js bdd jasmine jasmine-jquery

我正在尝试使用 Jasmine(带有 yaml 配置的 gem)来测试 Backbone.js 应用程序。我正在使用像 Todo example 这样的下划线模板.

template: _.template($('#item-template').html())

我的问题是我无法在我的模型/ View 之前加载模板,因此模板调用导致这些类在加载时出错。

我读过关于 jasmine-jquery 插件来做 fixtures 但问题是我的 src 文件(模型/ View )正在加载并且在我获得 spec 文件并且能够设置所需的 fixtures 之前失败.

如何尽早加载模板以用于重置我的类(class)?

最佳答案

您可以延迟 jQuery 选择器直到您需要它:

render: function(){
  var templateHtml = $(this.template).html();
  _.template(templateHtml);
}

或者您可以在 View 初始化时运行选择器:

initialize: function(){
  this.template = _.template($(this.template).html());
}

或者,如果您真的想保留代码原样并在定义 View 时让选择器求值,您可以将所有主干代码包装在一个函数中,当您想要初始化整个应用程序代码时调用该函数...例如真实 HTML 页面上的 jQuery $(function(){} 函数,或 Jasmine 测试中的 beforeEach 函数:

MyApp = (function(){
  var myApp = {};<p></p>

<p>myApp.MyView = Backbone.View.extend({
    template: _.template($("#item-template").html())
    // ...
  });</p>

<p>return myApp;
});
</p>

然后在您的应用中启动它:

$(function(){
  var myApp = MyApp();
  new myApp.MyView();
  // ...
});

在你的 Jasmine 测试中:

describe("how this thing works", function(){
  beforeEach(function(){
    var myApp = MyApp();
    this.view = new myApp.MyView();
    // ...
  });
});

一旦您准备好这些解决方案之一,您就可以使用 Jasmine-jQuery 之类的东西来加载您的固定装置。

FWIW:我倾向于根据需要结合使用这些技术。

关于templates - 使用模板进行 Jasmine 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7876480/

相关文章:

c++ - 为什么模板定义中不允许使用结构?

javascript - Backbone.js - 将 JSON 数组获取到 View 模板中

ruby-on-rails - Rails BDD 与 Cucumber : no such file to load -- cucumber-rails

java - 如何使用具有正常 "Given"语句的示例表(Parametrised Scenarios)

c++ - 模拟模板类的静态构造函数

c++ - 从模板特化中获取对类成员的访问

C++ 继承、模板和覆盖

javascript - 使用 Backbone.js 和 Underscore.js 的应用程序

node.js - 使用Backbone.js框架如何进行ajax调用快速路由

.net - SpecFlow - 找不到一个或多个步骤的匹配步骤定义