'How to mock @Viewchild MatInput in angular unit test cases
I am trying to mock viewchild in my angular test cases.
here is my html file
<mat-form-field appearance="fill">
<mat-label>Date</mat-label>
<input matInput #dateInput [matDatepicker]="picker"
(dateChange)="dateChange($event)" readonly>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<br />
<button (click)= "clear()">Clear</button>
ts
@ViewChild("toDateInput", { read: MatInput }) dateInput!: MatInput;
clear(){
this.dateInput.value=''
}
spec file
it("DateChange", () => {
expect(component.dateInput.value).toEqual('');
})
This unit test case getting fail and giving the error "Cannot set properties of undefined (setting 'value')", when I debug component.dateInput getting undefined. Can anyone help me to pass this unit test case
Solution 1:[1]
In this case, you need to provide a mock directive of MatInput, so ViewChild could read it from toDateInput element.
You can use ng-mocks for that.
beforeEach(() => {
return TestBed
.configureTestingModule({
imports: [
MockModule(MatInputModule), // <- ng-mocks
// ...
],
})
.compileComponents();
});
// ...
it('tests', () => {
// works now
expect(component.dateInput.value).toEqual('');
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | satanTime |
