gpt4 book ai didi

javascript - 使用 jasmine 和 backbone 测试表单提交。

转载 作者:行者123 更新时间:2023-11-29 18:27:04 25 4
gpt4 key购买 nike

我想用jasmine测试表单提交。
表单在主干 View 中定义,如下所示 (1)。
我实现了下面的测试(2),但我不确定它的效果如何。
例如,如果文本区域为空,则应调用 onError 函数。
在这种情况下,使用 jasmine 测试表单提交的最佳方法有什么想法吗?


(1)

var MyView = Backbone.View.extend({

events: {
'focus [data-tid="message"]' : 'focusForm',
'blur [data-tid="message"]' : 'blurForm',
'submit form' : 'submitForm'
},

focusedClass: 'is-form-focused',

focusForm: function () {
this.$el.find('form').addClass(this.focusedClass);
},

blurForm: function () {
this.$el.find('form').removeClass(this.focusedClass);
},

submitForm: function (event) {
event.preventDefault();

var formElement = event.currentTarget,
message = this.$el.find('.message');

if (formElement.checkValidity && !formElement.checkValidity()) {
this.onError();
} else {
// makes a POST ajax call
backendController.submitFeedback(message.val()).done(this.onSuccess).fail(this.onError);

}
},

onError: function () {
this.$el.find('.message').focus();
},

onSuccess: function () {
this.$el.find('.message').val('');
this.$el.find('form').removeClass(this.focusedClass);
}
});

(2)

describe('When Submit button handler fired', function () {
beforeEach(function () {
this.popupSpy = sinon.spy();
this.view.render();
this.view.$el.find('form').on('submit', this.popupSpy);
this.view.$el.find('form').trigger('submit');
});
it('submitForm should be called', function () {
expect(this.popupSpy.callCount).toBe(1);
});
});

最佳答案

在您的示例中,您正在测试自己的测试。

我宁愿提出这样的建议:

// code simplified and no tested
describe("When Submit button handler fired", function () {
it("submitForm should be called", function () {
this.view.render();
spyOn( this.view, "submitForm" );
this.view.$el.find("form").submit();
expect( this.view.submitForm ).toHaveBeenCalled();
});
});

更新

可能我上面的代码不会工作,因为在 spying over Router methods 中处理程序在初始化时设置,因此不会调用任何进一步的 spy

您应该在实例化 View 之前在类级别进行监视:

// code simplified and no tested
describe("When Submit button handler fired", function () {
it("submitForm should be called", function () {
spyOn( MyView.prototype, "submitForm" );

this.view = new MyView();
this.view.render();

this.view.$el.find("form").submit();

expect( MyView.prototype.submitForm ).toHaveBeenCalled();
});
});

关于javascript - 使用 jasmine 和 backbone 测试表单提交。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11953393/

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