加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 5组件测试选择和触发事件

发布时间:2020-12-17 17:23:51 所属栏目:安全 来源:网络整理
导读:我有一个有下拉列表的组件.更改后,它会触发一个事件,该事件通过数组进行过滤,以根据事件值从数组中获取selectedProduct. 我的代码如下: public onProductChanged(event): void { this.selectedProduct = this.products.find((product: Products) = product.
我有一个有下拉列表的组件.更改后,它会触发一个事件,该事件通过数组进行过滤,以根据事件值从数组中获取selectedProduct.

我的代码如下:

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

我的选择下拉菜单:

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

产品对象是一个对象:

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

这一切都有效,但我想在我的组件测试中测试,更改选择值会触发事件并检索正确的值.

我的测试代码如下:

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.如何使用下拉列表中更改的值触发事件?

解决方法

事实证明,在之前我没有通过调用就为函数设置了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',() => {

      productSelectElement.nativeElement.value = 1;
      productSelectElement.nativeElement.dispatchEvent(new Event('change'));

      fixture.detectChanges();

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

    });
  });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读