0
votes

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?

1
Instead of change event you can try using ngModelChange event and add ngModel to your input. On component init set the value of ngModel so that function associated with ngModelChange event will be called.Shrutika Patil
@Shrutika thanks, I have changed the code accordingly but, if you mean that change event will be triggered automatically upon assigning a value to the ngModel then, it isn't working for me. I have to explicitly call the change event for that and still, the method is getting the argument value as an empty string "".Saurabh Gupta

1 Answers

0
votes

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
      });
    }