How to mock an ElementRef that is passed into a method

Viewed 1192

I would like to write a test for a method that receives an ElementRef. I don't find a way to mock the ElementRef, can anyone help? Thanks so much!

exampleService.service.ts:

export class exampleService {
    exampleMethod(elRef: ElementRef): string {
      const elWidth = elRef.nativeElement.offsetWidth;
      return elWidth;
    }
}

testfile.service.spec.ts:

describe('ExampleService', () => {
  let service: ExampleService;
  beforeEach(() => { 
    service = TestBed.inject(ExampleService);
  });

  it('How to mock the ELEMENTREF?', () => {
    expect(service.exampleMethod(ELEMENTREF)).toBe('100');
  });

});

1 Answers

You can create the object with necessary properties and methods that you need to use with ElementRef object:

const mockElementRef: any = {
  nativeElement: {
    offsetWidth: 100
  }
};


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


.......


it('How to mock the ELEMENTREF?', () => {
  expect(service.exampleMethod(mockElementRef)).toBe('100');
});
Related