在组件单元测试中模拟指令输出
Simulate directive output in component unit test
我的 Angular 5 组件使用 typeahead directive of ngx-bootstrap,像这样:
<input [(ngModel)]="inputted"
[typeahead]="days"
(typeaheadOnSelect)="select($event)"
class="form-control">
现在我想测试当用户在预先输入中选择一个项目时,我的组件是否按照预期执行。我需要模拟 typeahead 指令的 typeaheadOnSelect
输出。如何在我的单元测试中访问该指令,以手动发出 typeaheadOnSelect
事件?到目前为止,我已经走到了这一步:
const elem: DebugElement = fixture.debugElement.query(By.css('input'));
这给了我输入元素。我如何从那里找到底层的 typeahead 指令?
如 中所述,可以从注入器中检索指令实例:
import { TypeaheadDirective } from 'ngx-bootstrap';
...
const elem: DebugElement = fixture.debugElement.query(By.css('input'));
const dir = elem.injector.get(TypeaheadDirective);
一种正确的方法是将单元测试与第三方单元隔离开来,并为 ngx-bootstrap 指令提供存根,而不是导入其模块。存根可以选择将其外部暴露为局部变量,而不是使用注入器来获取 class 个实例:
let typeaheadOutput;
...
@Directive({ selector: '[typeahead]' }
class TypeaheadDirectiveMock {
@Input() typeahead;
@Output() typeaheadOnSelect = typeaheadOutput = new EventEmitter();
}
TestBed.configureTestingModule({ declarations: [TypeaheadDirectiveMock], ...})
.compileComponents();
我的 Angular 5 组件使用 typeahead directive of ngx-bootstrap,像这样:
<input [(ngModel)]="inputted"
[typeahead]="days"
(typeaheadOnSelect)="select($event)"
class="form-control">
现在我想测试当用户在预先输入中选择一个项目时,我的组件是否按照预期执行。我需要模拟 typeahead 指令的 typeaheadOnSelect
输出。如何在我的单元测试中访问该指令,以手动发出 typeaheadOnSelect
事件?到目前为止,我已经走到了这一步:
const elem: DebugElement = fixture.debugElement.query(By.css('input'));
这给了我输入元素。我如何从那里找到底层的 typeahead 指令?
如
import { TypeaheadDirective } from 'ngx-bootstrap';
...
const elem: DebugElement = fixture.debugElement.query(By.css('input'));
const dir = elem.injector.get(TypeaheadDirective);
一种正确的方法是将单元测试与第三方单元隔离开来,并为 ngx-bootstrap 指令提供存根,而不是导入其模块。存根可以选择将其外部暴露为局部变量,而不是使用注入器来获取 class 个实例:
let typeaheadOutput;
...
@Directive({ selector: '[typeahead]' }
class TypeaheadDirectiveMock {
@Input() typeahead;
@Output() typeaheadOnSelect = typeaheadOutput = new EventEmitter();
}
TestBed.configureTestingModule({ declarations: [TypeaheadDirectiveMock], ...})
.compileComponents();