【问题标题】:Simulate directive output in component unit test在组件单元测试中模拟指令输出
【发布时间】:2018-07-20 23:06:53
【问题描述】:

我的 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 指令?

【问题讨论】:

    标签: angular unit-testing angular5


    【解决方案1】:

    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();
    

    【讨论】:

      猜你喜欢
      • 2019-06-25
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多