skip to content
Alvin Lucillo

Empty nativeElement in ng test

/ 1 min read

💻 Tech

During your unit testing in Angular, it’s important that the component you’re testing is rendered, especially if you’re going to check some DOM elements. For example, in the sample code below, Component1 seems to be empty compared to when you inspect the elements in Chrome DevTools. To fix that, ensure that you import all the modules that your component depends on.

component = TestBed.createComponent(Component1).componentInstance;

console.log(component.nativeElement);
/*
<div id="root0" _nghost-a-c3628110027="" ng-version="17.3.7" class="box-row-expand"></div>
*/
TestBed.configureTestingModule({
    declarations: [Component1],  // Declare the component to be tested
    imports: [CommonModule]  // Import CommonModule to use directives like ngIf and other modules
}).compileComponents();
    ```