gpt4 book ai didi

javascript - 使用 Jasmine 测试 Backbone View 时,浏览器页面不断刷新

转载 作者:搜寻专家 更新时间:2023-11-01 04:26:41 24 4
gpt4 key购买 nike

运行下面的 Jasmine 测试(1),测试成功,但我面临主测试页面的递归加载。

这是我的测试 (1),这是我运行测试的模块 (2):

有什么想法吗?我该如何解决这个问题?

附言:
该问题仅与 Chrome 和 Safari 浏览器有关。
这是一个例子:jsfiddle.net/shioyama/EXvZY


(1)

describe('When Submit button handler fired', function () {
beforeEach(function () {
spyOn(MyView.prototype, 'submitForm');
this.view = new MyView();
this.view.render();
this.view.$el.find('form').submit();
});

it('submitForm should be called', function () {
expect(MyView.prototype.submitForm).toHaveBeenCalled();
});
});

(2)

var MyView = Backbone.View.extend({
events: {
'submit form' : 'submitForm'
},

submitForm: function (event) {
event.preventDefault();
// some code
}
});

最佳答案

Backbone 使用委托(delegate)事件,这些事件在创建 View 时被绑定(bind)。您的 view.el 在创建时不包含表单,而是您在 render 方法中创建了一个表单。这就是提交委托(delegate)事件未被绑定(bind)的原因,而是您在页面上提交表单。该表单提交到相同的 URL,这会触发 Jasmine 套件再次运行,从而导致循环。

如果稍微修改一下代码,您会发现此版本可以正常工作,因为

元素在生成 View 之前就已存在。

var MyView = Backbone.View.extend({
events: {
'submit form' : 'submitForm'
},

submitForm: function (event) {
event.preventDefault();
// some code
}
});

//start test runner right after we're done defining our tests in this script
window.setTimeout( function(){
jasmine.getEnv().addReporter(new jasmine.TrivialReporter());
jasmine.getEnv().execute();
}, 0 );

//TESTS GO HERE
describe('When Submit button handler fired', function () {
beforeEach(function () {
spyOn(MyView.prototype, 'submitForm').andCallThrough();
this.view = new MyView({
el: $('<div><form><input type="submit" value="Submit" /></form></div>')
});
this.view.$el.find('form').submit();
});

it('submitForm should be called', function () {
expect(MyView.prototype.submitForm).toHaveBeenCalled();
});
});​

关于javascript - 使用 Jasmine 测试 Backbone View 时,浏览器页面不断刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11986605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com