首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >fixture.debugElement.componentInstance和fixture.nativeElement有什么不同?

fixture.debugElement.componentInstance和fixture.nativeElement有什么不同?
EN

Stack Overflow用户
提问于 2019-06-07 11:29:33
回答 1查看 4.5K关注 0票数 9

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

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

我是一个全新的角度测试新手,我正在将它应用到我的项目中,但我对此感到有点困惑。

代码语言:javascript
复制
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!');
  }));
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-08 16:29:02

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

fixture.nativeElementfixture.debugElement.nativeElement是一回事。这是由Angular在DOM中生成的HTML元素,在测试组件的模板中指定。通过nativeElement,您可以访问和测试屏幕上可视化的内容,在上面的测试中,H1的文本内容是否为Welcome to the app。请记住,例如,在By.css()这样的测试中,fixture.debugElement还有其他有用的方法和属性。

fixture.componentInstance使您可以访问component类。这允许您测试组件的公共API。在上面的测试中,您将检查应用程序组件的title属性是否为app

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

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56487593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档