简体   繁体   English

使用Jasmine测试Backbone视图时,浏览器页面会保持刷新

[英]Browser page keeps refreshing when testing Backbone views with Jasmine

Running the following Jasmine test(1), the test is successfully performed but I face the recursive loading of the main test page. 运行以下Jasmine测试(1),测试成功执行但我面临主测试页面的递归加载。

Here is my test (1) and here the module on which I am running the test (2): 这是我的测试(1),这里是我运行测试的模块(2):

Any ideas? 有任何想法吗? How can I fix the issue? 我该如何解决这个问题?

PS: PS:
The issue regard just Chrome and Safari Browser. 该问题只涉及Chrome和Safari浏览器。
Here is an example: jsfiddle.net/shioyama/EXvZY 这是一个例子:jsfiddle.net/shioyama/EXvZY


(1) (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) (2)

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

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

Backbone uses delegate events , which are bound when the view is created. Backbone使用委托事件 ,这些事件在创建视图时绑定。 Your view.el does not contain a form when it is created, but instead you're creating one in the render method. 您的view.el在创建时不包含表单,而是在render方法中创建表单。 That's why the submit delegate event does not get bound, and instead you're submitting the form on the page. 这就是为什么提交委托事件不受约束,而是您在页面上提交表单。 That form submit goes to the same URL, which triggers the Jasmine suite to be run again, resulting in a loop. 该表单提交到同一个URL,触发Jasmine套件再次运行,从而产生循环。

If you modify your code a bit, you'll find that this version works, as the <form> element exists before the view is generated. 如果您稍微修改一下代码,您会发现此版本有效,因为在生成视图之前<form>元素存在。

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();
    });
});​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM