Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protractor locator for formControlName

I'm using model based forms where my form looks like:

<form [formGroup]="form" (ngSubmit)="onSubmit(form.value)">
  <input type="text" formControlName="username">
  <input type="password" formControlName="password">
  <button type="submit" [disabled]="!form.valid">Submit</button>
</form>

I want to write a protractor spec to test the login. I would like to do something like the following in my spec:

    element(by.formControlName('username')).sendKeys('[email protected]');

This obviously doesn't work so is there a way to locate by form controls or am I resigned to the fact that I have to put a class or ID on the input fields?

like image 916
Mark Kenny Avatar asked Oct 07 '16 13:10

Mark Kenny


1 Answers

You can write a rather simple CSS selector:

element(by.css("input[formControlName=username]")).sendKeys('[email protected]');

Note that if you need to do this often, you can always define a reusable custom locator:

by.addLocator('formControlName', function(value, opt_parentElement, opt_rootSelector) {
  var using = opt_parentElement || document;

  return using.querySelectorAll('[formControlName="' + value +'"]');
});

Usage:

element(by.formControlName('username')).sendKeys('[email protected]');
like image 127
alecxe Avatar answered Nov 08 '22 11:11

alecxe