i created a component using angular material, and i would like to test it.
These are the versions of angular and angular materials:
- Angular 9.1.4
- Angular Material 9.2.2
The view has this code to render the datepicker:
<input
hidden
matInput
[matDatepicker]="datePickerCalendar"
(dateChange)="onCalendarChange($event)"
/>
<mat-datepicker-toggle matPrefix [for]="datePickerCalendar"></mat-datepicker-toggle>
<mat-datepicker #datePickerCalendar startView="multi-year"> </mat-datepicker>
The controller get the datepicker element in this way:
@ViewChild('datePickerCalendar') public datePickerCalendar: MatDatepicker<Date>;
and this is the method called when dateChange is triggered from the date picker:
public onCalendarChange(e: MatDatepickerInputEvent<Moment>): void {
this.datePickerCalendar.close()
}
So my question is, how can i implement an unit test that create the component and, when this method is called, will call the close() method without errors?
This is my current unit test:
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [
MatIconModule,
MatFormFieldModule,
MatInputModule,
MatDatepickerModule,
MatNativeDateModule,
NoopAnimationsModule,
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('clearing values', () => {
beforeEach(() => {
component.value = new DateObj(1, 1, 2000);
});
it('should clear day to null, no changes for month/year', fakeAsync(() => {
component.clearDay();
component.valueChange.subscribe((dateObj: DateObj) => {
expect(dateObj.day).toEqual(null);
expect(dateObj.month).toEqual(1);
expect(dateObj.year).toEqual(2000);
});
}));
});
});
I tried to search online but i didn't find anything to implement datepicker unit test. The only good tutorial was this one from angular material website (link) but it didn't explain how to test angular material datepicker.
Thank you
datePickerCalendar
. – Alexander Staroselskyopened
,closed
and or tracking the calls to those methods. Also keep in mind you can see how the material team tests date pickers: github.com/angular/components/blob/… . Start with querying the el – Alexander Staroselsky