[英]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. 更改后,它会触发一个事件,该事件通过数组进行过滤,以根据事件值从数组中获取selectedProduct。
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. 已调用productChanged事件并且该测试通过。 My selectedProduct is however always null. 但是,我的selectedProduct始终为null。 How do I get the event to fire using the changed value in the dropdown? 如何使用下拉列表中更改的值触发事件?
Turns out that in the before each I had set a spyOn for the function without a call through. 事实证明,在之前我没有通过调用就为函数设置了spyOn。 Working code is as follows: 工作代码如下:
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" });
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.