在组件单元测试

时间:2018-02-10 07:28:27

标签: angular unit-testing angular5

My Angular 5组件使用typeahead directive of ngx-bootstrap,如下所示:

<input [(ngModel)]="inputted"
   [typeahead]="days"
   (typeaheadOnSelect)="select($event)"
   class="form-control">

现在我想测试我的组件在用户选择typeahead中的项目时执行预期的操作。我需要模拟typeahead指令的typeaheadOnSelect输出。如何在单元测试中访问该指令,以手动发出typeaheadOnSelect事件?到目前为止,我已经达到了这一点:

const elem: DebugElement = fixture.debugElement.query(By.css('input'));

给了我输入元素。如何从那里找到基础的typeahead指令?

1 个答案:

答案 0 :(得分:2)

this answer中所述,可以从进样器中检索指令实例:

import { TypeaheadDirective } from 'ngx-bootstrap';

...
const elem: DebugElement = fixture.debugElement.query(By.css('input'));
const dir = elem.injector.get(TypeaheadDirective);

正确的方法是将单元测试与第三方单元隔离,并为ngx-bootstrap指令提供存根,而不是导入其模块。存根可以选择将其外部作为局部变量公开,而不是使用注入器来获取类实例:

let typeaheadOutput;

...
@Directive({ selector: '[typeahead]' }
class TypeaheadDirectiveMock {
  @Input() typeahead;
  @Output() typeaheadOnSelect = typeaheadOutput = new EventEmitter();
}

TestBed.configureTestingModule({ declarations: [TypeaheadDirectiveMock], ...})
.compileComponents();
相关问题