psugar
psugar

Reputation: 1895

Angular directive testing select options

How do you select an option in an angular directive test?

 var options = elem.find('#test-code-select option');
 expect(angular.element(options[0]).text()).to.equal('234');
 expect(angular.element(options[1]).text()).to.equal('236');

These work fine, but how do I manually force the selection of an option?

angular.element(options[1]).click(); //nope
angular.element(options[1]).trigger('click'); //nope
angular.element(options[1]).attr('selected', true); //nope

EDIT:

The directive template includes a select with an internal ng-model, I suspect this is the cause of the problem:

<select id='test-code-select' ng-options='code as code for code in codeList' ng-model='code'>

Upvotes: 6

Views: 6593

Answers (4)

Chen XI
Chen XI

Reputation: 11

I added this as another approach besides what has been answered by @ejain.

If you have jquery avaiable (i.e., not jqLite), I think the following should also work by triggering change on option:

var select = elem.find('#test-code-select');
var oneOption = select.find('option:contains("236")');
oneOption.prop('selected', 'selected').trigger('change');
expect(scope.code).toEqual('236');

Upvotes: 0

thirumalaa srinivas
thirumalaa srinivas

Reputation: 3640

// UPDATE: to select multiple values pass an array
// select is selector for <select> tag, preferrably ID
select.val(['236', '479']).change();

Upvotes: 0

ejain
ejain

Reputation: 3614

This works for me:

var select = elem.find('#test-code-select');
select.val('236').change();
expect(scope.code).toEqual('236');

Note the call to change().

Upvotes: 11

Adam McCormick
Adam McCormick

Reputation: 1670

If you just want to test the click handler then you just need to trigger a click event:

angular.element(options[1]).trigger('click');

You may have to allow the various handlers to execute by using $timeout.flush(), $scope.apply(), and/or by putting your verification code in a $timeout block.

Upvotes: 0

Related Questions