2

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


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

1 回答 1

4

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

我宁愿提出这样的建议:

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

更新

可能我上面的代码行不通,因为就像监视路由器方法一样,处理程序是在初始化时设置的,因此spy不会再调用任何进一步的代码。

您应该在类级别和实例化视图之前进行间谍活动:

// 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();
  });
});
于 2012-08-14T14:52:38.687 回答