sandeep ghansiala
sandeep ghansiala

Reputation: 11

TypeError: this.modal.nativeElement.present is not a function at myComponent.ngAfterViewInit

My Component code snippet:

export class MyComponent {
//reference to modal (a  UI component of external library)
@ViewChild('modal') public modal: ElementRef;

    constructor(private zone: NgZone) {}

    public ngAfterViewInit(): void {
        this.modal.nativeElement.present();
        this.closeModalAndEmitEventBind = this.closeModalAndEmitEvent.bind(this);
        this.modal.nativeElement.addEventListener(closeButtonClickedEventName, this.closeModalAndEmitEventBind);
        this.modal.nativeElement.addEventListener(modalDismissedEventName, this.closeModalAndEmitEventBind);
    }
}

Template code snippet

<ext-lib-modal #modal>
    // not so interesting code
</ext-lib-modal #modal>

.spec code snippet:

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [],
      providers: [],
    schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    component.modal = {
      nativeElement: {
        present: jasmine.createSpy('present'),
        addEventListener: jasmine.createSpy('addEventListener'),
        removeEventListener: jasmine.createSpy('removeEventListener'),
        dismiss: jasmine.createSpy('dismiss'),
      },
    };
    fixture.detectChanges();
  });

  describe('the constructor', () => {
    it('should render the component', () => {
        //even if I comment all of below expectations, I still get the same error 
        expect(component).toBeTruthy();
        expect(component.ngOnInit).toBeDefined();
        expect(component.ngAfterViewInit).toBeDefined();
        expect(component.ngOnDestroy).toBeDefined();
    });
  });
});

Error I'm getting: TypeError: this.modal.nativeElement.present is not a function at myComponent.ngAfterViewInit

What I tried I tried to inject mock ElementRef in spec providers like below, but I sill got the same error:

beforeEach(() => {
    modalElementMock = {
        nativeElement: {
        present: jasmine.createSpy('present'),
        addEventListener: jasmine.createSpy('addEventListener'),
        removeEventListener: jasmine.createSpy('removeEventListener'),
        dismiss: jasmine.createSpy('dismiss'),
        },
    };
});

beforeEach(async () => {
    await TestBed.configureTestingModule({
        declarations: [MyComponent],
        imports: [],
        providers: [
        {
            provide: ElementRef,
            useValue: modalElementMock,
        },
    ],
    schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
});

Can you help me find the solution for this issue?

Upvotes: 1

Views: 131

Answers (0)

Related Questions