Saurabh Gupta
Saurabh Gupta

Reputation: 345

(Jasmine)How do I programmatically select/pass the value <select> tag and trigger the change event in Angular 4?

I am working on an angular application and I am using Jasmine for unit testing it. I am new to Jasmine.

What I want is to test <select> tag for (change) event and the change event is triggered when the user selects a value from the drop-down list.

code to be tested:

// template
<select class="selectTerminal"(change)="onChangeTerminal($event.target.value)">
  <option value="" disabled>Select Terminal</option>
  <option *ngFor="let terminal of terminalList" [value]="terminal.id">{{terminal.terminalCode}}</option>
</select>

//function called when the change event is triggered.
onChangeTerminal(id) {

  // `id` comes as `undefined` upon `ng test`, but works fine with `ng serve` since the value is selected manually from the dropdown list.
  this.terminalId = id; 
  this.wharfService.getWharfOrderByTerminalId(id).subscribe(res => {
  }, (error) => {
    // handle error
  });
}

what I am so far able to do is trigger the change event so that the function is being called. But, I am not able to select/pass the value programmatically, which should be passed as arguments to the method that takes id upon selecting the value from the dropdown list.

How do I set the value of select options before triggering the change event?

Upvotes: 0

Views: 574

Answers (1)

Shrutika Patil
Shrutika Patil

Reputation: 565

Please try the following code. It should call onChange function automatically whenever model value changes

 // template
    <select class="selectTerminal"(change)="onChangeTerminal($event.target.value)" [(ngModel)]="selectedTerminal">
      <option value="" disabled>Select Terminal</option>
      <option *ngFor="let terminal of terminalList" [value]="terminal.id">{{terminal.terminalCode}}</option>
    </select>

    ngOnInit(){
        this.selectedTerminal = 'defaultTerminal';
    }
    //function called when the change event is triggered.
    onChangeTerminal(id) {

      // `id` comes as `undefined` upon `ng test`, but works fine with `ng serve` since the value is selected manually from the dropdown list.
      this.terminalId = id; 
      this.wharfService.getWharfOrderByTerminalId(id).subscribe(res => {
      }, (error) => {
        // handle error
      });
    }

Upvotes: 0

Related Questions