使用带有@ViewChild的MatInput元素,在运行规格时结果变量将不可使用

问题描述 投票:0回答:1

我在旧页面中有一个搜索组件,我正在尝试为此编写一些测试,但是这让我有些悲伤

这是模板

<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

为什么输入变量在此测试的组件范围中不可用?或有什么更好的解决方案来进行测试?

angular unit-testing angular-material
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.