Ian Meikle
Ian Meikle

Reputation: 23

Test to verify that component element exists in DOM - Jasmine & Angular

Hello Stack Overflow Community,

I’m having issues writing a simple Jasmine Unit Testing in Angular 5 to verify the existence of an element in the DOM for components. I have a successful test for standard HTML elements, such as p: expect(fixture.debugElement.query(By.css('p')).nativeElement).toBeTruthy();

But, this results in a TypeError: Cannot read property 'nativeElement' of null for Angular components. As an example, a Movie Component with a selector of app-movie:

it ('should have a element selector called app-root in DOM', () => { expect(fixture.debugElement.query(By.css(‘app-movie’)).nativeElement).toBeTruthy();

Can you please advise how to do this? Many thanks!

Upvotes: 2

Views: 8904

Answers (2)

Jeremias Nater
Jeremias Nater

Reputation: 803

Accessing the Element with..

fixture.debugElement.query(...).nativeElement

..should work, so i assume that your element couldn't be found inside of the debugElement. To prevent this from happening i suggest that you add a Test before accessing the nativeElement:

const debugMovieElement = fixture.debugElement.query(By.css('app-movie'))

expect(debugElement).toBeTruthy();
expect(debugElement.nativeElement).toBeTruthy();

(although checking for the nativeElement is probably not necessary after you checked the debugElement, but its what you were trying to do)

Upvotes: 1

Jry9972
Jry9972

Reputation: 473

Check on the debug element rather than its native Element.

const debugElement = fixture.debugElement.query(By.css('p'));
expect(debugElement).toBeTruthy();

If we test it on the native element as per the problem description, then the Jasmine will throw an error if the element is not found as the debugElement itself will be empty(null). Sample error:

TypeError: Cannot read property 'nativeElement' of null

Upvotes: 4

Related Questions