Search code examples
angularunit-testingtestingangular-cli

What is different between fixture.debugElement.componentInstance and fixture.nativeElement?


In this sample test file I saw two different syntax

one is const app = fixture.debugElement.componentInstance; and another is const compiled = fixture.nativeElement; I don't know what is different between these two syntax?

I am totally new with angular testing and I am applying it to my project but it is confused to me a little bit about this.

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!');
  }));
});

Solution

  • DebugElement is a wrapper across native elements and tested component allowing test to run on all supported platforms.

    fixture.nativeElement and fixture.debugElement.nativeElement are the same things. This is HTML element generated in the DOM by Angular as specified in the tested component's template. Through nativeElement you can access and test what visualized on the screen, in your test above whether the text content of the H1 is Welcome to the app. Keep in mind fixture.debugElement has other methods and properties that are useful in tests like By.css() for example.

    fixture.componentInstance gives you access to the component class. This allows you to test the public API of your component. In you test above you are whether the title property of you app component is app.

    You can check the Angular's testing guide for more detailed information.