我正在尝试使用 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/