4

I'm trying to emulate a user story on my website with Protractor.

The user has to type in an input that uses auto-completion. In real life, the user has to type some text in the input, then select the right proposition with either her mouse or more naturally her downarrow key.

The problem is that I can't seem to simulate that with Protractor. element.sendKeys just does not allow you to do that. I have tried in a dozen different manners and it yields unpredictable results at best.

So I would like to manipulate the ng-model behing my input directly. Is there a way to access the scope of an element from Protractor and call functions/set properties on it?

Here is a simplified version of my problem :

View :

<div ng-controller="MyController"> 
  <input id="my-input" ng-model="myModel"/>
</div>

Controller :

 myModule.controller('MyController', ['$scope', function($scope){
   $scope.myModel = "";
   //[...]
 }]);

e2e Protractor test :

describe("setting myModel to a fixture value", function(){
  it("should set myModel to 'a test value'", function(){
    var myInput = element('my-input');
    // Now what?
  });
});
Valentin Waeselynck
  • 5,950
  • 26
  • 43
  • Some fiddle, or some code snippet? – Kamran Ahmed Apr 15 '14 at 09:00
  • I have added some code snippets. – Valentin Waeselynck Apr 15 '14 at 09:16
  • is `element('my-input');` your real code? The sequence I would try is `myInput.click()` to give it focus, then `myInput.sendKeys('beginningOfAnAutoCompletedWord');` then `myInput.sendKeys('Protractor.Key.ARROW_DOWN');`. Then, depending on your implementation you can click or send a tab or Enter key. – glepretre Apr 17 '14 at 08:08
  • That's quite interesting, I had failed to find mention of the arrow keys in the docs, thank you! As a matter of fact, I have finally found a workaround to click on my dropdown menu for my own particular instance of this problem. However, I think the question of accessing angular models in itself deserves an answer, and I cannot close the question on this anyway, it would be misleading. – Valentin Waeselynck Apr 18 '14 at 13:19

2 Answers2

6

You can use .evaluate() to set your model value directly:

var elm = element(by.model("obj.field"));
elm.evaluate("obj.field = 'test';");

To get the model value:

elm.evaluate("obj.field").then(function (value) {
    console.log(value);
});
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Nice answer, can I use it somehow dynamic? e.g app.setDatepicker = function(path, date) { var elm = element(by.model(path)); elm.evaluate(path + " = " + date); }; – artdias90 Feb 11 '16 at 10:23
  • 1
    @artdias90 yes, sure, these are just strings, you can concatenate them - watch the quotes though. – alecxe Feb 11 '16 at 14:33
4

In this answer: How to select option in drop down protractorjs e2e tests

They use this: .sendKeys(protractor.Key.ARROW_DOWN); for sending DOWN arrows.

It worth a try.

Community
  • 1
  • 1
Lajos Veres
  • 13,595
  • 7
  • 43
  • 56