Search code examples
angularjasmineangular-test

Destroy undefined in Jasmine Test


I am writing test cases for .ts file. when i run the command ng test its getting failed. I have tried to mock the destroy method inside beforeEach still getting failed.

Component.ts

    export class DepComponent implements OnInit, OnDestroy {
      public _ref: any;
      deleteme(): void {
        //console.log(id);
        this.removeObject();
        this.nodedetaildelete.emit();
       }
       removeObject() {
        this.markcomponentdispose = true;
        console.log("delted component!");
        this._ref.destroy();
      }
}

Component.spec.ts

        describe('DeploycomponentComponent', () => {
          let component: DeploycomponentComponent;
          let fixture: ComponentFixture<DeploycomponentComponent>;
        
          beforeEach(async () => {
            await TestBed.configureTestingModule({
              declarations: [ DeploycomponentComponent ]
            })
            .compileComponents();
          });
        
          beforeEach(() => {
            fixture = TestBed.createComponent(DeploycomponentComponent);
            component = fixture.componentInstance;
            fixture.detectChanges();
          });
        
         it('should call deleteme', () => {
            let response = component.deleteme();  
            let resp = component.removeObject();
            spyOn(component._ref,'destroy')
            expect(response).not.toBeNull();
          });
    });

When i run the ng test it getting failed showing the below error enter image description here


Solution

  • I don't see where could set the value for your _ref member in the class based on your component.

    In your case, it would be easy to just assign a value for your _ref beforehand:

    it('should call deleteme', () => {
      // Mock this before you actually call your testing methods
      component._ref = {
        destroy: () => {}
      };
    
      let response = component.deleteme();
      let resp = component.removeObject();
      spyOn(component._ref,'destroy')
      expect(response).not.toBeNull();
    });