【问题标题】:How to compile html in angular 2?如何在 Angular 2 中编译 html?
【发布时间】:2016-04-20 20:29:38
【问题描述】:

我开始学习 Angular 2 并希望通过单元测试来解决问题。所以我希望我所有的指令/组件都用测试来编写。

在 angularJS(第一个版本)中测试指令你使用$compile。这是文档中的示例:

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

如何在angular 2中编译html文本写测试?

我想测试最简单的指令:

import {Component} from 'angular2/core';
@Component({
  selector: 'email',
  template: `Hello Email`
})
export class EmailComponent {
}

【问题讨论】:

  • 这个问题不是很清楚。您问的是如何在 Angular 2 中使用 Angular 1 的概念,但 Angular 2 是从头开始编写的,考虑到了不同的设计理念,而且这些概念甚至都不相似。
  • 重点是我想测试这个最简单的指令,不知道怎么做:/
  • 测试指令与编译 HTML 有什么关系?
  • 正如您在 angular1 示例中看到的 - 很多

标签: angularjs angular


【解决方案1】:

使用TestComponentBuilder,如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();
             });
       }));

【讨论】:

  • 再难不过了:/ 我只想测试最简单的指令(已编辑问题)
  • 我不使用 TS,因此我没有创建自定义答案。有很多例子。基本上你只需要注入TestComponentBuilder 并调用createAsync(MyComponent) 并使用它。我没有仔细看上面测试示例中的其他代码是做什么的。异步执行增加了一些额外的复杂性。
猜你喜欢
  • 2016-12-23
  • 2019-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 2017-04-25
  • 2016-12-20
  • 1970-01-01
相关资源
最近更新 更多