1

I'm trying to test a select element...

  <select [ngModel]="selectedRouters" name="routerName" class="form-control" id="routersSelect" size="12" (ngModelChange)="selectRouters($event)" multiple>
    <option [value]="router.name" *ngFor="let router of routers$ | orderBy : 'name'">
      {{router.name}}
    </option>
  </select>

with the method looking like:

selectRouters(routers) {
    this.routers$
        .filter(router => routers.includes(router.name))
        .forEach(router => router.setSelected(true))

    this.routers$
        .filter(router => !routers.includes(router.name))
        .forEach(router => router.setSelected(false))
}

The method is expecting string[] but I don't know how to test this...

//before
component = fixture.componentInstance

//it
component.selectedRouters = Array.of(r.name);

let evt = document.createEvent('Event');
evt.initEvent('ngModelChange');

selector.dispatchEvent(evt);

// also tried

selector.dispatchEvent(new CustomEvent('ngModelChange') {
  detail: ["arg1"]
})

But the argument is called with an event type not string[] which is throwing errors in the code.

Does anyone know how to do this, or how I can test a select element being selected?

Alex
  • 587
  • 11
  • 31

2 Answers2

1

You can check by changing in HTML [(ngModel)]="selectedRouters and (ngModelChange)="selectRouters(selectedRouters)" as follows

<select [(ngModel)]="selectedRouters" name="routerName" class="form-control" id="routersSelect" size="12" (ngModelChange)="selectRouters(selectedRouters)" multiple>
    <option [value]="router.name" *ngFor="let router of routers$ | orderBy : 'name'">
      {{router.name}}
    </option>
  </select>

Or you can do like same as you did inside HTML Page and just change the component code as follow

In HTML page

  <select [ngModel]="selectedRouters" name="routerName" class="form-control" id="routersSelect" size="12" (ngModelChange)="selectRouters($event)" multiple>
    <option [value]="router.name" *ngFor="let router of routers$ | orderBy : 'name'">
      {{router.name}}
    </option>
  </select>

In Component page

    selectRouters(event) {
    this.routers$
        .filter(router => routers.includes(event.target.value.toString()))
        .forEach(router => router.setSelected(true))

    this.routers$
        .filter(router => !routers.includes(event.target.value.toString()))
        .forEach(router => router.setSelected(false))
}
-1

You can follow this code to resolve your concern. Hope this helps! Thank you.

Aman Gojariya
  • 1,289
  • 1
  • 9
  • 21