pgupta pgupta - 5 months ago 196
AngularJS Question

AngularJS: How to write Jasmine test for form submit?

I want to auto-submit a form which is in the directive template. Below is the directive code for the same:

link: function(scope, el) {
$timeout(function() {
el.submit();
});
}


How to write Jasmine test for this piece of code?

Answer

I was able to solve my problem by spying on the submit function and delegating the call to the supplied function.

This goes in beforeEach block:-

element = angular.element(html);
compiledDirective = _$compile_(element)($scope);
$scope.$digest();
form = element[0];
spyOn(form, 'submit').and.callFake(function() {
    return false;
});

And then test your code for submit in the it() function:-

it('check if it submits the form', function() {
    $timeout.flush();
    expect(form.submit).toHaveBeenCalled();
});
Comments