0

I am developing my own website. I am new to Angular and just based on learing and online posts, I started developing my website. While running tests, I faced an error for getting h1 tag value.

I developed routes. One of the routes that AppComponent loads is HomeComponent in which h1 tag is available.

In app.component.spec.ts file, below is failed to get value of h1.

it('should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to jc-web!');});

Can anyone suggest how I can fetch h1 value from HomeComponent in the above code?

Appreciate your help.

2 Answers2

3

In order to access the h1 value inside HomeComponent, which is nested inside AppComponent, you'll need to either provide the actual HomeComponent in your TestBed:

TestBed.configureTestingModule({
    declarations: [
        AppComponent,
        HomeComponent
    ]
});

or else provide a stubbed version for your test to use. If you choose to provide the actual component, you must also include all of its dependencies. There's a more detailed explanation on how to test nested components in the Angular documentation here.

codequiet
  • 1,102
  • 5
  • 9
  • On a related note, Karma is usually used for unit tests, meaning you shouldn't need to check the DOM of another component. Is there a reason you don't want to put your test in the spec.ts file for HomeComponent? – codequiet Dec 18 '18 at 08:09
  • I moved my above code to home.component.spec.ts file and testing passed. Thanks for the help. – Rambabu Kokkiligadda Dec 18 '18 at 08:41
1

You just need to add the following code in the app.component.ts file.

title = 'the title';

it(`should have as title 'the title'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('the title');

});

This is in the app.component.spec.ts file

export class AppComponent {
title = ‘the title’ ;
}

This is in the app.component.ts file