【问题标题】:What is different between fixture.debugElement.componentInstance and fixture.nativeElement?fixture.debugElement.componentInstance 和 fixture.nativeElement 有什么不同?
【发布时间】:2019-10-22 13:32:12
【问题描述】:

在这个示例测试文件中,我看到了两种不同的语法

一个是const app = fixture.debugElement.componentInstance;,另一个是const compiled = fixture.nativeElement;,不知道这两种语法有什么不同?

我对角度测试完全陌生,我正在将它应用到我的项目中,但我对此有点困惑。

describe('AppComponent (initial CLI version)', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
  it(`should have as title 'app'`, async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('app');
  }));
  it('should render title in a h1 tag', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');
  }));
});

【问题讨论】:

    标签: angular unit-testing testing angular-cli


    【解决方案1】:

    DebugElement 是一个跨原生元素和测试组件的包装器,允许测试在所有支持的平台上运行。

    fixture.nativeElementfixture.debugElement.nativeElement 是同一个东西。这是 Angular 在 DOM 中生成的 HTML 元素,在测试组件的模板中指定。通过nativeElement你可以访问和测试屏幕上显示的内容,在你上面的测试中H1的文字内容是否为Welcome to the app。请记住,fixture.debugElement 具有在测试中有用的其他方法和属性,例如 By.css()

    fixture.componentInstance 让您可以访问组件类。这允许您测试组件的公共 API。在您上面的测试中,您的应用组件的标题属性是否为app

    您可以查看Angular's testing guide了解更多详细信息。

    【讨论】:

    • 是的。感谢您提供有关By.css() 的信息。我想我现在有点明白了。
    猜你喜欢
    • 1970-01-01
    • 2011-05-22
    • 2015-11-04
    • 2012-10-30
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多