我目前正在整理一些在组件级别测试Angular 2应用程序的最佳实践.

我见过一些教程查询Fixture的NativeElement对象中的 Select 器等,例如

it('should render "Hello World!" after click', async(() => {
    builder.createAsync(HelloWorld).then((fixture: ComponentFixture<HelloWorld>) => {
        fixture.detectChanges();
        let el = fixture.nativeElement;
        el.querySelector('h1').click();
        fixture.detectChanges();
            
        expect(el.querySelector('h1')).toHaveText('Hello World!');
    });
}));

然而,在juliemr's Angular 2 test seed年,她通过父DebugElement对象访问NativeElement.

it('should render "Hello World!" after click', async(() => {
    builder.createAsync(HelloWorld).then((fixture: ComponentFixture<HelloWorld>) => {
      fixture.detectChanges();
      let compiled = fixture.debugElement.nativeElement;
      compiled.querySelector('h1').click();
      fixture.detectChanges();
            
      expect(compiled.querySelector('h1')).toHaveText('Hello World!');
    });
}));

是否有任何特定的情况下,你会使用fixture 的调试元素.nativeElement而不是它的nativeElement?

推荐答案

  • nativeElement返回对DOM元素的引用
  • DebugElement是一个Angular2类,它包含与调查元素或组件相关的所有类型的引用和方法(请参见source of DebugNode and DebugElement

Angular相关问答推荐

角material 17 -如何从Style.scss中的主题中获取原色

如果过滤器在rxjs流中触发,则返回空数组

带迭代的Angular 内容投影

使用`UrlHandlingStrategy`更改位置

一个接一个的Angular http请求,但只关心第一个

为什么初始化值为 1 的BehaviorSubject 不能分配给类型number?

Angular AuthGuard:不推荐使用 CanActivate 和 CanActivateChild.如何更换它们?

http 调用的 RxJs 数组

如何使用指令以Angular 传递默认值

过滤 ngfor Angular 的计数

角项目更新

在一个组件中创建多个表单

Angular2:更新数组时*ngFor不更新

Observable .do() 运算符 (rxjs) 的用例

更改 Select 选项时获取当前值

请添加@Pipe/@Directive/@Component 注解

如何在 Angular cli 项目中包含来自 node_modules 的assets

为什么 *ngIf 不适用于 ng-template?

Angular2:将数组转换为 Observable

@Input 属性在 Angular 2 的 onInit 中未定义