Angular 4: Jasmine: Failed: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of null

cannot read property 'nativeelement' of null angular 6
cannot read property of undefined jasmine angular 2
typeerror: cannot read property 'pipe' of undefined jasmine
cannot read property 'debugelement' of undefined
cannot read property 'triggereventhandler' of null
typeerror: cannot read property '0' of undefined angular test
cannot read property 'parammap' of undefined
typeerror: cannot read property 'getcomponentfromerror' of null

I am writing unit test cases using jasmine in angular 4 app. I am getting 'Cannot read property 'nativeElement' of null' every time, I don`t know why. What I am trying to do below is to check if button is clicked. Below are my code files.


spec file
import { Http, Response, RequestOptions, Request, ConnectionBackend } from '@angular/http';
import { DataShareService } from '../core/services/data-share.service';
import { scooterRepairService } from './services/scooterRepair.service';
import { Router } from '@angular/router';

import { scooterRepairUnitComponent } from './scooter-repair-Unit.component';
import { TestBed, ComponentFixture, async, inject } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { SelectItem, CheckboxModule, CalendarModule, MultiSelectModule } from 'primeng/primeng';
import { CoreUIModule } from 'core-ui';
import { RouterTestingModule } from '@angular/router/testing';


describe('scooterRepairUnitComponent', () => {
    let fixture: ComponentFixture<scooterRepairUnitComponent>;
    let component: any;
    let http: Http;
    let dataShare: DataShareService;
    let scooterRepairService: scooterRepairService;
    let router: Router
    let comp = new scooterRepairUnitComponent(http, dataShare, scooterRepairService, router);

    // service stubs to mock services
    let MockResponse = {
        navigate: jasmine.createSpy('Response')
    }

    let MockRequestOptions = {
        navigate: jasmine.createSpy('RequestOptions')
    }

    let MockRequest = {
        navigate: jasmine.createSpy('Request')
    }

    let MockConnectionBackend = {
        navigate: jasmine.createSpy('ConnectionBackend')
    }

    // async beforeEach
    beforeEach(async(() => {

        TestBed.configureTestingModule({
            declarations: [scooterRepairUnitComponent], // declare the test component
            imports: [FormsModule, CheckboxModule, CalendarModule, MultiSelectModule, CoreUIModule, RouterTestingModule],
            schemas: [NO_ERRORS_SCHEMA],
            providers: [Http,
                { provide: Response, useValue: MockResponse },
                { provide: RequestOptions, useValue: MockRequestOptions },
                { provide: Request, useValue: MockRequest },
                { provide: ConnectionBackend, useValue: MockConnectionBackend },
                DataShareService,
                scooterRepairService]

        })
            .compileComponents();  // compile template and css
        fixture = TestBed.createComponent(scooterRepairUnitComponent);
        component = fixture.componentInstance;
    }));



    // synchronous beforeEach -- used if component is having external templates
    beforeEach(() => {

        comp = new scooterRepairUnitComponent(http, dataShare, scooterRepairService, router);
    });   



    it('should', async(() => {
        spyOn(component, 'onClearClick');
         let de: DebugElement = fixture.debugElement.query(By.css('#clearSearch'));
         let el: HTMLElement = de.nativeElement;
        fixture.whenStable().then(() => {


            fixture.detectChanges();
            expect(component.onClearClick).toHaveBeenCalled();
        })
    }));

component.ts
import { Component, OnInit, ViewEncapsulation, ElementRef, Output, Input } from '@angular/core';
import { Pipe, PipeTransform, Inject } from '@angular/core';
import { Http, Response, RequestOptions, Request, ConnectionBackend } from '@angular/http';
import { IScooter } from './models/Scooter';
import { IShop } from './models/shop';
import { ISelectedTab } from './models/selectedTab';
import { RestClientService, EnvironmentService } from 'core-shared/core.service';
import { Observable } from 'rxjs/Observable';
import { DataShareService } from '../core/services/data-share.service';
//mport { CommonService } from '../shared/services/common.service';
import { NgForm, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { SelectItem } from 'primeng/primeng';
import { ScooterRepairService } from './services/ScooterRepair.service';


@Component({
    selector: 'Scooter-repair-Unit',
    templateUrl: './Scooter-repair-Unit.component.html',
    styleUrls: ['./Scooter-repair-Unit.component.scss'],
    encapsulation: ViewEncapsulation.None,
})

export class ScooterRepairUnitComponent {
    selectedTab: string = 'ScooterRepair';
    showRepairUnitSelection: boolean=true;
    showScooterRepairUnit:boolean=true;

    showShopRepairUnit:boolean=false ;
    showMissingRepairUnit:boolean=false;
    showAddScooterRepairUnit:boolean=false;
    showAddShopRepairUnit: boolean = false;
    showScooterRepairUnitResultGrid = false;

    ScooterRepairUnitSearchTitle= 'Search Scooter Repair Unit Threshold';
    ScooterRepairUnitSearchResult= 'Scooter Repair Unit Results';
    shopRepairUnitSearchTitle= 'Search Shop Repair Unit Threshold';
    shopRepairUnitSearchResult= 'Shop Repair Unit Results';
    missingRepairUnitSearchResult= 'Missing Repair Unit Results';
    updateRepairUnitTitle= 'Update Results';
    gridPageSize: number;

    Scooters: IScooter[];

    errorMessage: string;

    ScooterRepairs: IScooter[] = [];
    canSubmitAuditRequest = false;
    totalScooterRepairRecords: number;
    isValidated: boolean;
    isSubmittedSuccessfully: boolean;
    clearScooterRepairSearch: boolean;

    constructor(private http: Http,
        private dataShare: DataShareService,
      //  private commonService: CommonService,
        private ScooterRepairService: ScooterRepairService,
       // private loggerService: LoggerService,
       // private storageService: StorageService,
        private router: Router) {
        this.gridPageSize = 10;
    }
     onSelectionChange(tabname) {
        this.SetTab(tabname);
     }


  private SetTab(tabname: string){
    this.showScooterRepairUnit = false;
         this.showShopRepairUnit = false ;
         this.showMissingRepairUnit = false;
     if (tabname === 'ScooterRepair') {
         this.showScooterRepairUnit = true;
     }

     if (tabname === 'shopRepair') {
         this.showShopRepairUnit = true ;
    }
    if (tabname === 'missingRepair') {
         this.showMissingRepairUnit = true;
      }
}

   ngOnInit(): void {
        this.setBreadCrumb();
        this.setLastSearch();
        this.selectedTab = 'ScooterRepair';
    }

   private setBreadCrumb() {
        // Setting Page title
        this.dataShare.setData('appTitle', 'Repair Unit Maintenance');

        // Setting Breadcrumb
        this.dataShare.setData('breadcrumbItems', [
        { label: 'Business Rule Engine' },
        { label: 'Repair Unit Maintenance', url: '/cra' }
    ]);
    }


    onClearClick()
    {
        this.clearScooterRepairSearch = true;
    }

}

HTML File
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" *ngIf="showRepairUnitSelection">
    <div class="panel ">
<form class="form-horizontal scooterUnitSearchForm" #requestauditsearchform="ngForm" action="#" >

                <div class="form-group ">  
                    <div class="col-lg-12 col-xs-12 clearfix">
                    <label for="" class=" col-lg-2 col-xs-6 control-label">
                        Search By:
                    </label>              
                    <label class="control-label radio-inline">
                                <input  type="radio" id="showscooter" name="mainTab" [(ngModel)]="selectedTab" value="scooterRepair" (change)="onSelectionChange(selectedTab)" 
                                 [checked]="selectedTab === scooterRepair">
                                    scooter Repair Unit 
                    </label>
                     <label class=" control-label radio-inline">
                              <input type="radio"  name="mainTab"  id="showShop"  [(ngModel)]="selectedTab" value="shopRepair" (change)="onSelectionChange(selectedTab)" 
                                [checked]="selectedTab === shopRepair"> 
                             Shop  Repair Unit 
                     </label>
                    <label class=" control-label radio-inline">
                              <input type="radio"  name="mainTab"    id="showMissingscooter"  [(ngModel)]="selectedTab" value="missingRepair"(change)="onSelectionChange(selectedTab)" 
                               [checked]="selectedTab === missingRepair"> 
                             Missing scooter Repair Unit
                     </label>

                </div>
                </div>           
</form>
</div>
  </div>

<div class="col-lg-12 col-mg-12 col-sm-12 col-xs-12">
    <collapse-expand-frame 
        [frametitle]="scooterRepairUnitSearchTitle" *ngIf="showscooterRepairUnit">
        <scooter-repair-Unit-search

            (requestscooterRepairSearch)="searchscooterRepairRequest($event)" 
            [clearscooterRepairSearch]="clearscooterRepairSearch"
        >
        </scooter-repair-Unit-search>
    </collapse-expand-frame> 

</div>


<div class="row" style="Margin-bottom:20px" *ngIf="showscooterRepairUnit">
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 ">
                <div class="form-group">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-sm-right text-md-right text-right">
                    <button pButton type="button" label="Add Repair Unit" (click)="onAddscooterRepair()" class="btn btn-default"></button>
                    <button pButton type="button" label="Search" class="btn btn-default"></button>
                    <button pButton type="button" label="Clear" (click)="onClearClick()" class="btn btn-default"></button>                
                    </div>
                </div>
            </div>
              </div>
<div class="col-lg-12 col-mg-12 col-sm-12 col-xs-12 clearfix"  *ngIf="showAddscooterRepairUnit">


<collapse-expand-frame >
        <add-scooter-repair-Unit

            (requestscooterRepairSearch)="searchscooterRepairRequest($event)" 
        >
        </add-scooter-repair-Unit>
</collapse-expand-frame >

</div>

<div class="col-lg-12 col-mg-12 col-sm-12 col-xs-12">
<collapse-expand-frame 
    [frametitle]="scooterRepairUnitSearchResult" *ngIf="showscooterRepairUnit">
    <scooter-repair-Unit-search-grid 

    >
    </scooter-repair-Unit-search-grid >
</collapse-expand-frame>
</div>

<div class="col-lg-12 col-mg-12 col-sm-12 col-xs-12">
<collapse-expand-frame 
    [frametitle]="updateRepairUnitTitle" *ngIf="showscooterRepairUnit">
    <update-scooter-repair-Unit
    >
    </update-scooter-repair-Unit>
</collapse-expand-frame>
</div>

<div class="col-lg-12 col-mg-12 col-sm-12 col-xs-12">
    <collapse-expand-frame 
        [frametitle]="shopRepairUnitSearchTitle"  *ngIf="showShopRepairUnit">
        <shop-repair-Unit-search
       >
        </shop-repair-Unit-search>

    </collapse-expand-frame> 
</div>



         <div class="row" style="Margin-bottom:20px" *ngIf="showShopRepairUnit">
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 ">
                <div class="form-group">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-sm-right text-md-right text-right">
                    <button pButton type="button" label="Add Repair Unit" (click)="onAddShopRepair()" class="btn btn-default"></button>
                    <button pButton type="button" label="Search" class="btn btn-default"></button>
                    <button pButton type="button" label="Clear" id="clearSearch" (click)="onClearClick()"  class="btn btn-default"></button>
                    </div>
                </div>
            </div>
              </div>

    <div class="col-lg-12 col-mg-12 col-sm-12 col-xs-12">
    <collapse-expand-frame 
          *ngIf="showAddShopRepairUnit">
        <add-shop-repair-Unit
       >
        </add-shop-repair-Unit>

    </collapse-expand-frame> 
</div>

<div class="col-lg-12 col-mg-12 col-sm-12 col-xs-12">
<collapse-expand-frame 
    [frametitle]="shopRepairUnitSearchResult" *ngIf="showShopRepairUnit">
    <shop-repair-Unit-search-grid 

    >
    </shop-repair-Unit-search-grid >
</collapse-expand-frame>
</div>

<div class="col-lg-12 col-mg-12 col-sm-12 col-xs-12">
<collapse-expand-frame 
    [frametitle]="updateRepairUnitTitle" *ngIf="showShopRepairUnit">
    <update-shop-repair-Unit
    >
    </update-shop-repair-Unit>
</collapse-expand-frame>
</div>
<div class="col-lg-12 col-mg-12 col-sm-12 col-xs-12">
<collapse-expand-frame 
    [frametitle]="missingRepairUnitSearchResult" *ngIf="showMissingRepairUnit">
    <missing-repair-Unit-search-grid 
    >
    </missing-repair-Unit-search-grid>
</collapse-expand-frame>
</div>

I faced the same issue and I traced the problem back to the *ngIf statement on the div

you have to set a value for 'showscooterRepairUnit' on your test, Otherwise it will assume its false and set the css element null resulting the debugElement to be null

Running Jasmine tests: TypeError: Cannot read property , Running Jasmine tests: TypeError: Cannot read property 'nativeElement' of null #​19292. Closed To make it fail I added *ngIf to the H3 in welcome.component.ts. Without I just started Unit Testing in Angular 5 and this issue immediately presents itself ie +1 4. @trotyl. Copy link. Quote reply. Contributor  Uncaught (in promise): TypeError: Cannot read property 'call' of undefined TypeError: Cannot read property 'call' of undefined alan-agius4 added comp: devkit/build-angular and removed need: repro steps labels Oct 9, 2018

Workaround

If you are using *ngIf in the element, use hidden instead.

<h2 [hidden]="hideItem"> My Message</h2>

This error is caused when jasmine could not find that element in the DOM. The most common scenario is using *ngIf in the template. According to docs, *ngIf destroys the element from DOM, if the expression evaluates to false.

Failed: Uncaught (in promise): TypeError: Cannot read property , Failed: Uncaught (in promise): TypeError: Cannot read property 'response' of undefined #1334. Closed. Keithkdl opened this issue on Oct 4, 2017 · 3 comments false }, { pattern: 'node_modules/zone.js/dist/jasmine-patch.js', instrument: false } 'npm:@angular/platform-browser-dynamic/bundles/platform-​browser-dynamic  Read more about our automatic conversation locking policy. This action has been performed automatically by a bot. angular-automatic-lock-bot bot locked and limited conversation to collaborators Sep 15, 2019

I have a similar problem and able to solve it by using page object and querySelectorAll

fixture.nativeElement.querySelectorAll('button');

HTML:

 <div *ngIf="isAbbreviationsAvailable(element.description); then caseA else caseB"></div>
  <ng-template #caseA>
    <div>

      <ng-template #popContent class="popover">
       <span id="glossary" >  {{element.description| glossary:glossaryDescription}}</span>
          <button class="close" (click)="p.close()"><img src="assets/icons/close.svg"></button>

      </ng-template>

      <button class="popoverLink" [ngbPopover]="popContent" [autoClose]="false"
              triggers="manual" #p="ngbPopover" (click)="p.open()" placement="top-right bottom-right" container="body"
              html="true" >
        {{split(element.description)[0]}}
      </button>

      /{{split(element.description)[1]}}

    </div>
  </ng-template>
  <ng-template #caseB>{{element.description}}</ng-template>

Test case:

const template: HTMLElement[] = fixture.nativeElement.querySelectorAll('button');
let link: HTMLElement = template[8]

expect(link.textContent.trim()).toEqual('ACC');

Uncaught TypeError: Cannot read property 'length' of undefined , I have tried to test an angular component by using Jasmine and Karma. TypeError: Unable to get property 'map' of undefined or null reference I am now getting Uncaught (in promise): TypeError: Cannot read property 'create' of and fix the issue inside pace itself but I've already spent the good part of 3-4 hours trying to  If you only need to find out whether getFilterData is called or not, try returning a fake promise by faking the function: With jasmine 1.3, we could use andCallFake :

angular 2 “Failed: Cannot read property 'replace' of undefined” when , angular 2 “Failed: Cannot read property 'replace' of undefined” when running ng test - angular. to load app/banner.component.html Error: Uncaught (in promise​): Failed to load TypeError: Cannot read property 'textContent' of undefined WARN Karma and Jasmine seem to be working but the test command does not​  Failed to navigate:Cannot read property 'lng' of undefined.ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'lng' of undefined Ask Question Asked 2 years, 11 months ago

Angular Unit Testing–Cannot read property 'ngInjectableDef' of , TypeError: Cannot read property 'ngInjectableDef' of undefined. Googling around didn't really help, as everything seemed to be GitHub issues  The only catch in the middle of all of this is that i ended up upgrading from angular 4 to 5. Hope this helps anyone with the same type of issue (only took me around a day and a half to get it sorted lol) Current version: Angular CLI: 1.6.8 Node: 8.9.4 OS: win32 x64 Angular: 5.2.4 animations, common, compiler, compiler-cli, core, forms

Avoiding Common Errors in Your Jasmine Test Suite, As I've started to work more with Jasmine and Backbone.js, I've added some Todos(); 4 expect(todos.model). OK, we've got some failures - "TypeError: Cannot read property Uncaught SyntaxError: unexpected identifier. angular.js:13920 TypeError: Cannot read property 'hasOwnProperty' of undefined at auth.service.ts:138. This is causing the nav bar to display the logout button instead of login too, and I can access the profile page even though I haven't logged in.

Comments
  • How does the template look (where it's trying to find an element with id #clearSearch?
  • @FredrikLundin Below is the html for above code
  • Hmm, can't see that you added it
  • @FredrikLundin, please reload page, I have updated the question with html
  • @Maddy what is the value for debug element did you check in console it is comming up ? and can you have a plunker for the same