1

I started to learn angular 2 and want to get things right with unit test. So I want all my directives/components to write with tests.

In angularJS (first version) to test directive You use $compile. Here's example from doc:

  it('Replaces the element with the appropriate content', function() {
    var element = $compile("<a-great-eye></a-great-eye>")($rootScope);
    $rootScope.$digest();
    expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
  });

How to compile html text in angular 2 to write a test?

I want to test simpliest direcive:

import {Component} from 'angular2/core';
@Component({
  selector: 'email',
  template: `Hello Email`
})
export class EmailComponent {
}
piernik
  • 3,507
  • 3
  • 42
  • 84
  • Take a look at this question: http://stackoverflow.com/questions/32340641/angular-2-equivalent-of-ng-bind-html-sce-trustashtml-and-compile – Javier Núñez Jan 15 '16 at 09:21
  • this question isn't really clear. you are asking about how to use a concept from angular 1 in angular 2, but angular 2 was written from the ground up with a different design philosophy in mind, and the concepts aren't even similar. – Claies Jan 15 '16 at 09:52
  • Point is that I want to test this simpliest directive and don't know how:/ – piernik Jan 15 '16 at 10:01
  • what does testing a directive have to do with compiling HTML? – Claies Jan 15 '16 at 11:07
  • As You see in angular1 example - a lot – piernik Jan 15 '16 at 11:48

1 Answers1

1

Use TestComponentBuilder like shown in this example from https://github.com/angular/angular/blob/9e44dd85ada181b11be869841da2c157b095ee07/modules/angular2/test/common/directives/ng_for_spec.ts

it('should reflect added elements',
       inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
         tcb.overrideTemplate(TestComponent, TEMPLATE)
             .createAsync(TestComponent)
             .then((fixture) => {
               fixture.detectChanges();

               (<number[]>fixture.debugElement.componentInstance.items).push(3);
               fixture.detectChanges();

               expect(fixture.debugElement.nativeElement).toHaveText('1;2;3;');
               async.done();
             });
       }));
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    It couldn't be more difficult :/ All I wanted is to test simpliest directive (edited question) – piernik Jan 15 '16 at 09:32
  • 1
    I don't use TS therefore I didn't create a customized answer. There are tons of examples. Basically you just need to inject the `TestComponentBuilder` and call `createAsync(MyComponent)` and use it. I didn't have a closer look what the other code in the above test example does. Some additional complexity is added by async execution. – Günter Zöchbauer Jan 15 '16 at 09:34