【发布时间】:2020-09-23 18:31:52
【问题描述】:
我使用角材料创建了一个组件,我想对其进行测试。
这些是角材料和角材料的版本:
- Angular 9.1.4
- 角材料 9.2.2
视图有这个代码来呈现日期选择器:
<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>
控制器通过这种方式获取datepicker元素:
@ViewChild('datePickerCalendar') public datePickerCalendar: MatDatepicker<Date>;
这是从日期选择器触发 dateChange 时调用的方法:
public onCalendarChange(e: MatDatepickerInputEvent<Moment>): void {
this.datePickerCalendar.close()
}
所以我的问题是,我如何实现创建组件的单元测试,并且在调用此方法时,将调用 close() 方法而不会出错?
这是我当前的单元测试:
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);
});
}));
});
});
我尝试在线搜索,但没有找到任何可以实现 datepicker 单元测试的东西。 唯一好的教程是来自 angular material 网站 (link) 的教程,但它没有解释如何测试 angular material datepicker。
谢谢
【问题讨论】:
-
请展示您到目前为止的测试内容,包括渲染包含日期选择器的组件,包括注入所有必要的角度材料依赖项以及使用您链接到查询日期选择器的工具,以及设置为
datePickerCalendar找一些间谍。 -
@AlexanderStaroselsky 已更新
-
好的,很好。因此,您分享了有关使用线束的文档。您是否确定日期选择器是否存在测试工具?如果没有,您是否尝试过该文档中关于手动查询元素的共享内容?您首先查询呈现的日期选择器并评估对
opened、closed的更改,或者跟踪对这些方法的调用。另外请记住,您可以看到材料团队如何测试日期选择器:github.com/angular/components/blob/…。从查询el开始 -
谢谢@AlexanderStaroselsky 我知道你可以手动选择元素,但是,因为我阅读了有角度的材料提供了线束元素,我认为可能有一个用于 datepicker 以避免编写大量代码并在阅读/使用方面进行复杂的单元测试。但是我会更深入地了解这些我没有检查的部分,谢谢
标签: angular unit-testing angular-material