我在旧页面中有一个搜索组件,我正在尝试为此编写一些测试,但是这让我有些悲伤
这是模板
<mat-form-field class="flex-row">
<mat-icon matPrefix>search</mat-icon>
<input #searchInput matInput placeholder="Search" type="text" [value]="search">
<button mat-icon-button matSuffix (click)="clear()" *ngIf="searchInput.value">
<mat-icon>
close
</mat-icon>
</button>
</mat-form-field>
组件使用MatInput
作为@ViewChild
export class SearchComponent implements OnInit, OnDestroy {
searchUpdate: Subject<string> = new Subject();
@ViewChild(MatInput, { static: true }) public searchInput: MatInput;
(...)
clear(): void {
this.searchInput.value = '';
this.searchUpdate.next(this.searchInput.value);
}
}
我正在尝试测试clear()
功能:
it('should clear search', fakeAsync(() => {
component.searchInput.value = 'test';
spyOn(component.searchChanged, 'emit');
component.clear();
expect(component.searchChanged.emit).toHaveBeenCalledWith('');
}));
但是我得到了错误
TypeError:无法设置未定义的属性'value'
如果我在运行测试时检查component.searchInput
的值,则为undefined
为什么输入变量在此测试的组件范围中不可用?或有什么更好的解决方案来进行测试?