angular - 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。
我错过了什么?
谢谢
解决方案
当你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();
}));
推荐阅读
- php - Codeigniter URL 中的双斜杠问题
- time-complexity - 哈希表时间复杂度混淆
- html - 如何通过xpath在第一个子节点之前获取节点的文本?
- amazon-web-services - 查找 executionRoleArn、taskRoleArn 的值
- java - Java:处理文件时Arraylist超出范围
- laravel - 使用 Laravel Sanctum 进行 Vue SPA 身份验证
- javascript - 如何在反应中通过多个组件传递数据?
- python - OperatorNotAllowedInGraphError:不允许迭代 `tf.Tensor`:AutoGraph 确实转换了此函数
- swift - 布尔函数返回默认值,直到在 Firebase DB XCode Swift 中检查实际值
- python - 为数据框行随机分配 1 个值 - 需要帮助