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 {
}
5
  • Take a look at this question: stackoverflow.com/questions/32340641/… Commented Jan 15, 2016 at 9: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. Commented Jan 15, 2016 at 9:52
  • Point is that I want to test this simpliest directive and don't know how:/ Commented Jan 15, 2016 at 10:01
  • what does testing a directive have to do with compiling HTML? Commented Jan 15, 2016 at 11:07
  • As You see in angular1 example - a lot Commented Jan 15, 2016 at 11:48

1 Answer 1

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();
             });
       }));
Sign up to request clarification or add additional context in comments.

2 Comments

It couldn't be more difficult :/ All I wanted is to test simpliest directive (edited question)
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.