Don*_*lor 3 javascript backbone.js jasmine jasmine-jquery backbone-views
我正在使用Jasmine 2.0测试Backbone View.View在加载时生成初始ajax请求,以使用值填充其表单字段.我希望我的Jasmine测试(在it下面的函数中)仅在收到这些值后运行.
测试当前失败,因为在测试运行后似乎收到了ajax请求,即使我正在存根ajax请求.
我该怎么写这个测试?
describe('View', function() {
var formFieldValues = [/* blah */];
var view;
beforeEach(function(done) {
jasmine.Ajax.install();
jasmine.Ajax.stubRequest('/form-fields').andReturn({
responseJSON: formFieldValues
});
view = new View({el: $('<main></main>')}); // makes ajax call on initialization
$('body').append(view.el);
});
afterEach(function() {
view.remove();
jasmine.Ajax.uninstall();
});
it('form fields have values', function(done) {
// PROBLEM IS HERE: THE FOLLOWING RUNS BEFORE VIEW'S AJAX CALL FINISHES
expect(view.$('[name="fieldName"]').children().length).toEqual(formFieldValues.length);
});
});
Run Code Online (Sandbox Code Playgroud)
看起来你实际上并没有运行异步规范.我注意到你的beforeEach并且it都收到了一个done回调,但他们都没有这么称呼.如果您正在删除ajax,那么您可能不需要运行异步规范,因为存根将有效地使ajax请求同步.
当我运行以下代码时,一切正常.
规格:
describe('View', function() {
var formFieldValues = [{name: 'foo'}, {name: 'bar'}];
var view;
beforeEach(function() {
jasmine.Ajax.install();
jasmine.Ajax.stubRequest('/form-fields').andReturn({
responseText: JSON.stringify(formFieldValues)
});
view = new View(); // makes ajax call on initialization
});
afterEach(function() {
jasmine.Ajax.uninstall();
});
it('form fields have values', function() {
// PROBLEM IS HERE: THE FOLLOWING RUNS BEFORE VIEW'S AJAX CALL FINISHES
expect(view.$('[name="fieldName"]').children().length).toEqual(formFieldValues.length);
});
});
Run Code Online (Sandbox Code Playgroud)
我的虚拟实现:
Collection = Backbone.Collection.extend({
url: '/form-fields'
});
View = Backbone.View.extend({
initialize: function() {
this.collection = new Collection();
this.collection.on('reset', this.render, this);
this.collection.fetch({reset: true});
},
render: function() {
var innerEl = $('<div name="fieldName"></div>')
this.collection.each(function(item) {
innerEl.append('<span></span>');
});
this.$el.append(innerEl);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1419 次 |
| 最近记录: |