首页 > 解决方案 > Angular 10 Jasmine 组件在调用函数后不更新属性

问题描述

我正在调用一个在我的单元测试中将 int 值设置为 0 的函数。

这是UT的代码

it('should clear filters', fakeAsync(() => {
    spyOn(component, 'clearFilters');
    const button: HTMLElement = fixture.debugElement.nativeElement.querySelector('.mdi-filter-variant-remove');
    button.click();
    fixture.detectChanges();
    tick();
    expect(component.clearFilters).toHaveBeenCalled();
    expect(component.filtersCount).toBe(0);
    expect(component.clearFiltersEvent.emit).toHaveBeenCalled();
  }));

下面是该函数的部分代码:

clearFilters(): void {
   this.filtersCount = 0;

我不知道为什么 expect(component.filtersCount).toBe(0); 失败。它被设置为另一个不同于 0 的数字。其他期望正在工作。正在调用该函数。据我了解,由于调用了函数,因此该属性应为 0。

我错过了什么?

谢谢

标签: angularjasmine

解决方案


当你spyOn使用一个方法时,我们会丢失该方法的实现细节(基本上它返回 undefined 即使它被调用)。

要获得您想要的,请尝试:

it('should clear filters', fakeAsync(() => {
    spyOn(component, 'clearFilters').and.callThrough(); // add and.callThrough() so you don't lose implementation details
    const button: HTMLElement = fixture.debugElement.nativeElement.querySelector('.mdi-filter-variant-remove');
    button.click();
    fixture.detectChanges();
    tick();
    expect(component.clearFilters).toHaveBeenCalled();
    expect(component.filtersCount).toBe(0);
    expect(component.clearFiltersEvent.emit).toHaveBeenCalled();
  }));

推荐阅读