I want to test a directive with the current Angular2 version (RC6).
I'm reading from NG2 Test recipes that the way to go is creating an ad-hoc Component that implements your directive in the template.
@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
}));
})
Now this solution seems a bit hacky and adds complexity to a simple test by adding a class that could create errors on its own. What if i don't want to generate a new component only for this purpose? Is there a direct way to test a directive?
My directive:
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
}
}