'Angular e2e - should render title in a h1 tag
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.
Solution 1:[1]
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.
Solution 2:[2]
You just need to add the following code in the app.component.ts file.
title = 'the title';
app.component.spec.ts app.component.ts
You need to made the change in 2 files and the code will work fine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | codequiet |
Solution 2 | Aanchal Agarwal |