jeudi 30 novembre 2017

Angular 5 component testing select and triggered event

I have a component which has a dropdown. When changed it triggers an event which filters through an array to get the selectedProduct from an array based on the event value.

My code is as follows:

  public onProductChanged(event): void {
    this.selectedProduct = this.arrayProducts.find((product: Products) => product.id == event.target.value);
  }

My select dropdown:

<select id="product" (change)="onProductChanged($event)">
    <option>--- Please Select ---</option>
    <option *ngFor="let product of products" [value]="product.id">  </option>
</select>

The product object is an object:

{ "id": 1, "name": "name_here", "displayName": "Name Here" }

This all works however I want to test in my component test that changing the select value triggers the event and the correct value is retrieved.

My test code is as follows:

  describe('Product selection', () => {
    it('should select product', () => {

      expect(component.selectedProduct).toBeUndefined();
      productSelectElement.nativeElement.value = 'Product Name';
      productSelectElement.nativeElement.dispatchEvent(new Event('change'));

      fixture.detectChanges();

      expect(component.onProductChanged).toHaveBeenCalled();
      expect(component.selectedProduct).toEqual({ "id": 1, "name": "product_name", "displayName": "Product Name" });
    });
  });

The productChanged event has been called and that test passes. My selectedProduct is however always null. How do I get the event to fire using the changed value in the dropdown?

Aucun commentaire:

Enregistrer un commentaire