Angular 10 Jasmine 组件在调用函数后不更新属性
Angular 10 Jasmine component not updating properties after function is called
我在单元测试中调用了一个将 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。
我错过了什么?
谢谢
当您 spyOn
一个方法时,我们会丢失该方法的实现细节(基本上它 returns 未定义,即使它被调用)。
要得到你想要的,试试:
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();
}));
我在单元测试中调用了一个将 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。
我错过了什么?
谢谢
当您 spyOn
一个方法时,我们会丢失该方法的实现细节(基本上它 returns 未定义,即使它被调用)。
要得到你想要的,试试:
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();
}));