How to get the value of a select when using ngValue in Angular unit tests
Asked Answered
C

0

7

In my Angular app I have a <select> bound to a reactive form like the following:

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

At this stage, mySelectValues is an array of strings.

I do component dom testing like this:

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

This works fine. However, at some point, in some selects I needed to have Objects as values instead of plain strings/numbers in some places.

So I've changed my HTML code to use [ngValue] instead of [value]:

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

At this point, in my test the value of select.value is no longer 'ABC' but becomes something like '2: ABC' where 2 is the index of the selected option, then a column + space, then the actual value.

So far I can live with this, just by changing my test to:

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

And it keeps working. However, in some places, I need to use Objects as values, so mySelectValues will be not an array of plain strings/numbers, but an array of objects instead.

For example:

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

And so changing the HTML like this:

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

The select now works fine with objects. However, my test no longer works because select.value is now returning always values like '2: Object' because an object is selected and no longer a plain string.

How can I solve this problem?

In other words: given a <select> that uses <option> with [ngValue] bound to objects, how can I get the selected value of the <select> (accessing it via the DOM like in my original test case) ?

Columbarium answered 15/9, 2020 at 15:10 Comment(1)
Did you ever figure this out?Tasia

© 2022 - 2024 — McMap. All rights reserved.