我是Angular的新手,正在使用Karma对其进行测试。我正在尝试从模板中获取 mat-options 的实例,以验证其文本内容。不幸的是,我收到因果报应的空错误
TypeError:...中的optionDe为null >
这是测试代码:
// When option is selected to [1], set selected to that:
it(
'Should select Shoes Order Type: International',
() => {
const de: DebugElement = fixture.debugElement;
const optionDe = de.query(By.css('mat-option'));
const p: HTMLElement = optionDe.nativeElement;
expect(p.textContent).toEqual('');
}
);
这是模板代码:
<mat-form-field>
<mat-label>Order-Type:</mat-label>
<mat-select>
<mat-option
*ngFor="let type of orderTypes"
[value] = "type.name">
{{ type.name }}
</mat-option>
</mat-select>
</mat-form-field>
问题:
如何正确获取该mat-option
或模板中任何字段的引用,以免出现空指针异常并在测试中使用其属性?
答案 0 :(得分:0)
当然可以。您没有在共享的代码中初始化任何数据。尝试这样的事情。
// When option is selected to [1], set selected to that:
it('Should select Shoes Order Type: International',
() => {
// initialize the data in your component
fixture.component.orderTypes = [{name : 'opition1'}];
const de: DebugElement = fixture.debugElement;
const optionDe = de.query(By.css('mat-option'));
const p: HTMLElement = optionDe.nativeElement;
expect(p.textContent).toEqual('');
}
);
确保在规范的“描述”部分中包含MatSelectModule
TestBed.configureTestingModule({
imports: [
MatSelectModule,
NoopAnimationsModule,
],
declarations: declarations,
providers: [
],
}).compileComponents();