mercredi 23 mai 2018

Testing Mat Autocomplete in Form Component

I need your support for my question please. I want to Testing Mat Autocomplete in Form Component.

  1. My project is in Angular 5, Jasmine2.6.4
  2. My code project is like below. Please follow step by step my code.

Step1. Html Component

<form [formGroup]="addClientForm" (ngSubmit)="onAddClient()" class="col s12" materialize>
  <div class="row">
    <div class="input-field col s12">
      <input formControlName="client_name" id="client_name" type="text" class="validate" required="required" [ngClass]="{invalid: invalidinput}">
      <label for="client_name">Name *</label>
    </div>
  </div>
  <div class="row">
    <div class="input-field col s12">
      <textarea formControlName="address" id="address" class="validate materialize-textarea" required="" aria-required="true" [ngClass]="{invalid: invalidinput}">
        <label for="example" data-error="wrong" data-success="right">Field</label>
        </textarea>
      <label for="address">Address *</label>
    </div>
  </div>
  <div class="row">
    <div class="input-field col s12">
      <input formControlName="contactNo" id="contactNo" type="number" class="validate" required="" aria-required="true">
      <label for="contactNo">Contact Number *</label>
    </div>
  </div>
    <div class="row">
    <div class="input-field col s12">
      <input formControlName="country_id" id="country_id" matInput placeholder="Select Country*" aria-label="State" [matAutocomplete]="auto"
        autoActiveFirstOption [formControl]="country_id">
      <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayWith">
        <mat-option (onSelectionChange)="updateForm($event, country.country_id, 'country_id')" *ngFor="let country of filteredOptionsCountry | async"
          [value]="country.name">
          
        </mat-option>
      </mat-autocomplete>
    </div>
  </div>
     <div id="add_client_button_container" class="row">
    <button [disabled]="!addClientForm.valid || Waiting" id="add_client_button" type="submit" class="btn waves-effect waves-light">
      Register
    </button>
    <button id="cancel_button" (click)="onCancel()" class="btn waves-effect waves-light grey lighten-4 black-text">
      Cancel
    </button>
  </div>
</form>

Step 2. TS component

 filteredOptionsCountry: any;
  country_id: FormControl = new FormControl();
  constructor(private fb: FormBuilder,
    private router: Router,
    private clientService: ClientService,
    private cs: CountryService,
    public auths: AuthService
  ) {
    this.addClientForm = this.fb.group({
      'client_name': new FormControl('', [Validators.required, Validators.nullValidator]),
      'address': new FormControl('', Validators.required),
      'contactNo': new FormControl('', Validators.required),
      'country_id': new FormControl('', Validators.required),
    });
  }
  ngOnInit() {
    this.filteredOptionsCountry = this.country_id.valueChanges.pipe(
      startWith(''),
      map(val => this.filterCountry(val))
    );
    this.cs.getAllCountry().subscribe(
      countryes => {
        this.countryes = countryes.map((country) => {
          return new Country(country);
        });
      }
    );
  }

  onAddClient() {
    let client = this.addClientForm.value
    let newClient = new Client(client);
    this.ws.createClient(newClient).subscribe(
      result => {
        if (result === true) {
        } else {
        }
      }
    );
  }
  //Country
  filterCountry(val: string): Country[] {
    if (val) {
      let filterValue = val.toLowerCase();
      return this.countryes.filter(country => country.name.toLowerCase().startsWith(filterValue));
    }
    return this.countryes;
  }
 onCancel() {
    this.router.navigate(['/main/clients']);
  }
}

Step 3. I tried this code:

   describe('Component: Add Client', () => {
        let component: AddClientFormComponent;
        let fixture: ComponentFixture<AddClientFormComponent>;
        beforeEach(() => {
            TestBed.configureTestingModule({
                imports: [ReactiveFormsModule, FormsModule, HttpModule, RouterTestingModule,
                    MatInputModule,
                    MatButtonModule,
                    MatFormFieldModule,
                    MatAutocompleteModule],
                declarations: [AddClientFormComponent],
                providers: [AuthService, ClientService, CountryService],
            });
            fixture = TestBed.createComponent(AddClientFormComponent);
            component = fixture.componentInstance;
            component.ngOnInit();
        });
        it('Add Client', async(() => {
            let clientElement: DebugElement;
            let debugElement = fixture.debugElement;
            let authService = debugElement.injector.get(AuthService);
            let clientservice = debugElement.injector.get(ClientService);
            clientElement = fixture.debugElement.query(By.css('form'));
                component.addClientForm.controls['client_name'].setValue('ClientName'),
                component.addClientForm.controls['address'].setValue('address'),
                component.addClientForm.controls['contactNo'].setValue(123456),
                component.addClientForm.controls['country_id'].setValue(6),
                fixture.debugElement.query(By.css('form')).triggerEventHandler('submit', null);     
                fixture.detectChanges();
               clientElement.triggerEventHandler('ngSubmit', null);
        }));
    });

when run ng test in page show my form like in html, only country is empty input. My question is, how to testing Mat Autocomplete and how to submit these values?

Aucun commentaire:

Enregistrer un commentaire