在Angular单元测试中使用ngValue时如何获取选择的值

问题描述

在我的Angular应用中,我有一个<select>绑定到如下所示的反应形式:

<form [formGroup]="myForm">
  <select formControlName="myControlName" id="my-select">
    <option [value]="value" *ngFor="let value of mySelectValues">{{ value }}</option>
  </select>
</form>

在此阶段,mySelectValues一个字符串数组。

我这样component dom testing

it('the select should reflect the form value"',() => {

  // I somehow change the form value to 'ABC' here 
  // and I want to check if the select is correctly showing the change

  const select = fixture.nativeElement.querySelector('#my-select');
  expect(select.value).toEqual('ABC');
});

这很好。但是,在某些时候,在某些选择中,我需要使用Objects作为值,而不是某些地方的纯字符串/数字。

因此,我将HTML代码更改为使用[ngValue]而不是[value]

<option [ngValue]="value" ...

在这一点上,在我的测试中,select.value的值不再为'ABC',而是变成类似于'2: ABC'的值,其中2是所选选项的索引,然后一列+空格,然后是实际值。

到目前为止,只需将测试更改为:

expect(select.value).toEqual('2: ABC');

它一直在工作。但是,在某些地方,我需要使用对象作为值,因此mySelectValues不会是纯字符串/数字的数组,而是对象的数组。

例如:

mySelectValues = [
  { name: 'Name 1',value: 'MyTestValue1' },{ name: 'Name 2',value: 'MyTestValue2' },];

如此更改HTML:

<form [formGroup]="myForm">
  <select formControlName="myControlName" id="my-select">
    <option [ngValue]="object.value" *ngFor="let object of mySelectValues">{{ object.name }}</option>
  </select>
</form>

选择现在可以很好地与对象配合使用。但是,我的测试不再起作用,因为select.value现在总是返回'2: Object'之类的值,因为已选择了一个对象,而不再是纯字符串。

我该如何解决这个问题?

换句话说:给定一个<select>使用<option>并绑定了[ngValue]的对象,如何获得<select>的选定值(通过像我原始测试用例中的DOM)?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)