本文介绍了如何编译角2 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习角2,并希望得到正确的事情与单元测试。所以,我想我所有的指令/组件与测试写。

在angularJS(第一版)来测试指令,可以使用 $编译。下面是从文档的例子:

 它('替换为相应的内容元素',函数(){
    VAR元= $编译(<一个伟大眼>< / A-大眼>中)($ rootScope);
    $ rootScope $摘要()。
    期待(element.html())toContain(无盖,缭绕火焰,2次);
  });

如何编译HTML文本在角2编写测试?

我想测试simpliest direcive:

 进口{}组件从angular2 /核心;
@零件({
  选择:电子邮件,
  模板:`你好Email`
})
出口类EmailComponent {
}


解决方案

使用 TestComponentBuilder 像这个例子所示,从https://github.com/angular/angular/blob/9e44dd85ada181b11be869841da2c157b095ee07/modules/angular2/test/common/directives/ng_for_spec.ts

 它('应反映添加的元素',
       注([TestComponentBuilder,AsyncTestCompleter](TCB:TestComponentBuilder,异步)=> {
         tcb.overrideTemplate(TestComponent,模板)
             .createAsync(TestComponent)
             。然后((夹具)=> {
               fixture.detectChanges();               (小于数[]≥fixture.debugElement.componentInstance.items).push(3);
               fixture.detectChanges();               期待(fixture.debugElement.nativeElement).toHaveText(1; 2; 3;');
               async.done();
             });
       }));

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 {
}
解决方案

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

这篇关于如何编译角2 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:58