【问题标题】:Testing Angular2 Directive without creating a new Component在不创建新组件的情况下测试 Angular2 指令
【发布时间】:2016-09-13 11:15:37
【问题描述】:

我想用当前的 Angular2 版本 (RC6) 测试一个指令。

我从NG2 Test recipes 了解到,要走的路是创建一个临时组件,在模板中实现您的指令。

@Component({ 
  selector: 'container',
  template: `<div log-clicks (changes)="changed($event)"></div>`,
  directives: [logClicks]
})
export class Container {  
  @Output() changes = new EventEmitter();
  changed(value){
    this.changes.emit(value);
  }
}

describe('Directive: logClicks', () => {
  let fixture;
  beforeEachProviders(() => [ TestComponentBuilder ]);

  beforeEach(injectAsync([TestComponentBuilder], tcb => {
    return tcb.createAsync(Container).then(f => fixture = f);
  }));

  //specs
  it('should increment counter', done => {
    //... actual test
  }));
}) 

现在这个解决方案似乎有点老套,并且通过添加一个可能会自行产生错误的类来增加简单测试的复杂性。如果我不想仅为此目的生成新组件怎么办?有没有直接测试指令的方法?

我的指令:

import { Directive, Input, OnInit } from '@angular/core';
import { NgControl, Form} from '@angular/forms';

@Directive({
    selector: '[autoSave][formControlName],[autoSave][formControl],[autoSave][ngModel]'
})

export class AutoSave implements OnInit {
    constructor(public genericControl: NgControl) {  }
    @Input('autoSave') label: string;

    ngOnInit() {
       //stuff happens
    }
}

【问题讨论】:

    标签: angular angular2-directives angular2-testing


    【解决方案1】:

    您应该能够直接针对指令/组件进行测试。

    import { addProviders, async, inject, describe, expect, beforeEach, it, beforeEachProviders } from '@angular/core/testing';
    import { logClicks } from './logClicks';
    
    describe('App: List', () => {
      var component: logClicks;
    
      beforeEach(() => {
        component = new logClicks();
      });
    
      it('should create the app', () => {
          expect(component).toBeTruthy();
        });
    });
    

    由于您没有包含代码,因此我对您的指令做出了一些假设,但您应该能够针对您的指令创建这样的测试。

    【讨论】:

    • 对不起,你说得非常对,我刚刚添加了我的指令代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 2021-02-17
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    相关资源
    最近更新 更多