【问题标题】:(Jasmine)How do I programmatically select/pass the value <select> tag and trigger the change event in Angular 4?(Jasmine)如何以编程方式选择/传递值 <select> 标记并触发 Angular 4 中的更改事件?
【发布时间】:2019-03-12 10:32:52
【问题描述】:

我正在开发一个 Angular 应用程序,我正在使用 Jasmine 对其进行单元测试。我是 Jasmine 的新手。

我想要测试&lt;select&gt;标签的(更改)事件,当用户从下拉列表中选择一个值时触发更改事件。

要测试的代码:

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

到目前为止,我能做的是触发更改事件,以便 正在调用函数。但是,我无法选择/传递值 以编程方式,应该作为参数传递给方法 从下拉列表中选择值时获取 id。

如何在触发更改事件之前设置选择选项的值?

【问题讨论】:

  • 您可以尝试使用 ngModelChange 事件并将 ngModel 添加到您的输入中,而不是更改事件。在组件初始化时设置 ngModel 的值,以便调用与 ngModelChange 事件关联的函数。
  • @Shrutika 谢谢,我已经相应地更改了代码,但是,如果您的意思是更改事件将在为ngModel 分配值时自动触发,那么它对我不起作用。我必须为此显式调用更改事件,但该方法仍然将参数值作为空字符串""

标签: angular unit-testing jasmine karma-jasmine jasmine-jquery


【解决方案1】:

请尝试以下代码。只要模型值发生变化,它就会自动调用 onChange 函数

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    相关资源
    最近更新 更多