Angular 5 component testing select and triggered event

Discussão em 'Angular' iniciado por Steve Fitzsimons, Dezembro 15, 2024.

  1. 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.products.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"> {{ product.displayName }} </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?

    Continue reading...

Compartilhe esta Página