2017-11-30 7 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

이 products' 내가 그것을 배열했다 정교하게하려고 노력하지만 나는 그것을 할 수있는 유효한 시험이라고 생각 코드 사본의 나머지 붙여 –

+0

을 변경하는 것을 잊었다이라고 생각 다음과 같이 작동 코드는 :'component.onProductChanged ('Product Name'); fixture.detectChanges();'그리고 여전히 ** null **을 반환하는지 확인하십시오. 그럼 당신은 적어도 그것이 작동한다는 것을 압니다. 여전히 null을 반환하면 제품이 설정되지 않을 수 있습니다. – Swoox

+0

component.onProductChanged ({target : {value : 1}})로 시도해보십시오. 어느 doesnt 일. 그 값은 응용 프로그램에서 실행될 때 전달되는 값입니다. –

답변

1

각기 전에 호출없이 함수에 대해 spyOn을 설정했음을 알 수 있습니다. `될 운명

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

    }); 
    });