2017-11-30 9 views
2

私はドロップダウンを持つコンポーネントを持っています。変更すると、配列をフィルタリングしてイベント値に基づいて配列からselectedProductを取得するイベントをトリガします。次のように角5コンポーネントのテストで選択してトリガーしたイベント

私のコードは次のとおりです。

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

私の選択ドロップダウン:これはすべて私がテストしたいが働く

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

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

製品オブジェクトは、オブジェクトであります私のコンポーネントテストでは、選択値を変更するとイベントがトリガされ、正しい値が取得されます。

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

productChangedイベントが呼び出され、そのテストに合格し、次のように

私のテストコードがあります。しかし、私のselectedProductは常にnullです。ドロップダウンで変更された値を使用してイベントを発生させるにはどうすればよいですか?

+0

: 'component.onProductChanged( 'Product Name'); fixture.detectChanges(); 'を返し、それでも** null **が返されるかどうかを確認します。その後、あなたはそれが動作することを少なくとも知っています。それでもnullが返された場合は、商品が設定されていない可能性があります。 –

+0

の残りの部分を変更するのを忘れていることを詳しく説明しようとしていたと思う 'であることを意味し

beforeEach(() => { fixture = TestBed.createComponent(SelectProductsComponent); component = fixture.componentInstance; component.products = products; fixture.detectChanges(); productSelectElement = fixture.debugElement.query(By.css('#products')); spyOn(component, 'onProductChanged').and.callThrough(); expect(component.products).toEqual(products); expect(component.selectedProduct).toBeUndefined(); }); describe('Product selection',() => { it('should select product',() => { productSelectElement.nativeElement.value = 1; productSelectElement.nativeElement.dispatchEvent(new Event('change')); fixture.detectChanges(); expect(component.onProductChanged).toHaveBeenCalled(); expect(component.selectedProduct).toEqual({ "id": 1, "name": "product_name", "displayName": "Product Name" }); }); }); 
Swoox

+0

component.onProductChanged({target:{value:1}})で試してみました。それは動作しません。これは、アプリケーションで実行したときに渡される値です。 –

答えて

1

それぞれの前に、コールスルーなしで関数のspyOnを設定していたことが分かります。次のようにコードを作業するです:

products`は、私はそれが配列だったが、その後、私はそれを行うには、有効なテストだと思うのコードのコピーペースト
関連する問題