【发布时间】:2019-06-25 09:09:18
【问题描述】:
如何存根/模拟读取为ViewChild 的指令/组件?
例如,使用 angular.io 中的简单指令:
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor() { }
}
假设我正在测试AppComponent,并使用ViewChild 读取HighlightDirective:
@ViewChild(HighlightDirective) theHighlightDirective: HighlightDirective
而存根指令是:
@Directive({
selector: '[appHighlight]'
})
export class StubbedHighlightDirective {
constructor() { }
}
由于组件试图读取HighlightDirective,即使您在单元测试中声明StubbedHighlightDirective,theHighlightDirective 也将是undefined。
例子:
it('HighlightDirective is defined', () => {
// This test fails
expect(component.theHighlightDirective).toBeDefined();
});
如果您忽略 tslint 中的某些内容或使用 as 关键字,则可以解决此问题:
Version 1: Just ignore some things in tslint so compiler doesn't complain
it('HighlightDirective is defined', () => {
// Compiler will typically complain saying that
// StubbedHighlightDirective isn't assignable to type of HighlightDirective
component.theHighlightDirective = new StubbedHighlightDirective();
// this passes
expect(component.theHighlightDirective).toBeDefined();
});
Version 2: Use "as" keyword
it('HighlightDirective is defined', () => {
// Actually compiler will still complain with warnings
component.theHighlightDirective = new StubbedHighlightDirective() as HighlightDirective;
// this passes
expect(component.theHighlightDirective).toBeDefined();
});
是否有另一种方法可以彻底清除这类 ViewChild 引用?
【问题讨论】:
-
对不起,我不认为这是可能的
标签: angular unit-testing jasmine viewchild