AneeshPutturi
AneeshPutturi

Reputation: 768

How to create Unit test for ElementRef.nativeElement.querySelector()

I'm trying to test a component that has an ElementRef and accessing

import { Component, OnInit, ElementRef } from '@angular/core';

@Component({
  selector: 'component',
  templateUrl: '...',
  styleUrls: ['...']
})
export class MyComponent implements OnInit {

  constructor(private elementRef: ElementRef) {
    
  }

  ngAfterViewInit() {
    
  }

  ngOnInit() {

  }

childAdded(){
 if( this._elementRef?.nativeElement?.querySelector('#id'+ sectionIndex + '_' + (sectionItemIndex + 1))) {
                    this._elementRef.nativeElement.querySelector('#id' + sectionIndex + '_' + (sectionItemIndex + 1)).focus();
                } 
}

when user click button on UI childAdded is called where i need to focus the button

Code in spec file

import { ElementRef } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';

import { SectionItemCrudComponent } from './section-item-crud.component';
 class MockElementRef implements ElementRef {
    nativeElement = {
      querySelector :jasmine.createSpy(),
    };
  }
  
describe('SectionItemCrudComponent', () => {
  let component: SectionItemCrudComponent;
  let fixture: ComponentFixture<SectionItemCrudComponent>;
  
 

  const e1: ElementRef = new ElementRef({focus() {} } );
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ Component ],
      providers: [
        { provide: ElementRef, useClass: MockElementRef }
      ],
      imports: [TranslateModule.forRoot()],
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(SectionItemCrudComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
 describe('childAdded    funtion -> ', function () {
    it('should call childAdded focus  ', function () {
      
      component.childAdded   ();
      
    });
  });
});

I should add in the beforeEachProviders for the injection of ElementRef to be successful.When I run ng test I got Error: No provider for ElementRef! Please help me to write mock above method without changing code in the component.ts file

Upvotes: 1

Views: 579

Answers (0)

Related Questions