【问题标题】:Angular 10 Unit Testing PrimeNG p-dropdown with 2-Way Data BindingAngular 10 单元测试 PrimeNG p-dropdown 与 2-Way 数据绑定
【发布时间】:2022-03-26 17:50:18
【问题描述】:

在我的带有 Jasmine 测试框架的 Angular 10 应用程序中,我需要帮助测试带有 2 路数据绑定的 PrimeNG p-dropdown 在选择项目时自动更新我的模型。在下面的示例中,我将如何验证当一个项目被选中时,selectedCity(我的组件中的模型)是否得到更新?

在我的组件中使用的示例下拉列表:

<p-dropdown [options]="cities" [(ngModel)]="selectedCity"></p-dropdown>

下拉选项:

this.cities = [
    { label: 'Select City', value: null },
    { label: 'New York', value: { id: 1, name: 'New York', code: 'NY' } },
    { label: 'Rome', value: { id: 2, name: 'Rome', code: 'RM' } },
    { label: 'London', value: { id: 3, name: 'London', code: 'LDN' } },
    { label: 'Istanbul', value: { id: 4, name: 'Istanbul', code: 'IST' } },
    { label: 'Paris', value: { id: 5, name: 'Paris', code: 'PRS' } }
];

我在组件测试中尝试了以下方法无济于事,模型仍然未定义:

it('should populate the model when an item is selected', async(() => {
    fixture.detectChanges();
    fixture.whenStable().then(() => {
        const dropdown: Dropdown = fixture.debugElement.query(By.css('p-dropdown')).componentInstance;
        dropdown.selectItem(new Event('change'), dropdown.options[1].value);
        fixture.detectChanges();
        expect(component.selectedCity).toEqual(dropdown.options[1].value);
    });
}));

【问题讨论】:

  • 一般来说,您应该相信 primeNg 已经测试了他们自己的组件,并且您不需要自己测试它。您只应该检查您自己编写的代码。但是,如果您需要 PrimeNg 组件进行测试,最好模拟和使用间谍来满足您的需求

标签: angular typescript testing jasmine primeng


【解决方案1】:

它对我有用。

it('Setting Value of the ag via UI and using, async()=>{
    
    const ag = debugElement.query(By.css('.item-0 .p-element')).componentInstance;


    ag.selectItem(new Event('change'),'ag-1');
    fixture.detectChanges();

   
    expect(serviceMock.filterCustomers).toBeCalled();

    await expect(firstValueFrom(serviceMock.customers$)).resolves.toEqual(['C-1']);
  

  });

【讨论】:

  • 测试用例描述中缺少引号。
猜你喜欢
  • 2021-01-07
  • 1970-01-01
  • 2019-11-11
  • 2019-04-03
  • 2018-09-15
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 2018-06-10
相关资源
最近更新 更多