Setting view value an input field in a unit test of an angular form directive Setting view value an input field in a unit test of an angular form directive angularjs angularjs

Setting view value an input field in a unit test of an angular form directive


Here's how I've been unit testing my input-based directives (Lots of code omitted for clarity!) The important line you are after is:

angular.element(dirElementInput).val('Some text').trigger('input');

Here's the full unit test:

  it('Should show a red cross when invalid', function () {    dirElement = angular.element('<ng-form name="dummyForm"><my-text-entry ng-model="name"></my-text-entry></ng-form>');    compile(dirElement)(scope);    scope.$digest();    // Find the input control:     var dirElementInput = dirElement.find('input');    // Set some text!    angular.element(dirElementInput).val('Some text').trigger('input');    scope.$apply();    // Check the outcome is what you expect! (in my case, that a specific class has been applied)    expect(dirElementInput.hasClass('ng-valid')).toEqual(true);  });


The previous answer is correct if you are using Angular with jQuery but for Angular without jQuery (using jqlite) you can use triggerHandler instead (see here for full API)

it('foos to the bar', function() {  el.val('Foo').triggerHandler('input');  // Assuming el is bound to scope.something using ng-model ...  expect(scope.something).toBe('Foo');});