0

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
    }
}
Bolza
  • 1,904
  • 2
  • 17
  • 42

1 Answers1

1

You should be able to directly test against the directive/component.

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

I am making some assumptions about your directive as you didn't include the code, but you should be able to create a test like this against your directive.

Joffutt4
  • 1,418
  • 14
  • 15