user1015388
user1015388

Reputation: 1515

How to mock a nativeElement.focus() in Angular 4 spec file

I have a method which uses an ElementRef which is defined below.

@ViewChild('idNaicsRef') idNaicsRef: ElementRef;

ElementRef then sets the focus using .nativeElement.focus().

The method fails while running the spec, saying 'undefined is an object'

Upvotes: 9

Views: 13485

Answers (2)

risingTide
risingTide

Reputation: 1896

Although httpNick's answer should work, I ended up asking an architect on my team about this and he led me to a slightly different solution that may be a bit simpler.

describe(MyComponent.name, () => {

    let comp: MyComponent;

    describe('myFunction', () => {

        it('calls focus', () => {

            comp.idNaicsRef = {
                nativeElement: jasmine.createSpyObj('nativeElement', ['focus'])
            }

            comp.myFunction();

            expect(comp.idNaicsRef.nativeElement.focus).toHaveBeenCalled();
        });
    });

This particular example would just test to see if the focus method has been called or not. That's the test that I was interested in when I was testing my method, but you could of course test whatever you wanted. The key is the setup beforehand (which was elusive before it was shown to me).

Upvotes: 7

httpNick
httpNick

Reputation: 2624

this should work. this just creates a spy object and then you can populate it with whatever you want, so you could even check if it was called in your unit test.

  import createSpyObj = jasmine.createSpyObj;
  comp.idNaicsRef = createSpyObj('idNaicsRef', ['nativeElement']);
  comp.idNaicsRef.nativeElement = { focus: () => { }};

comp is the reference to the component you are testing.

createSpyObj comes from a jasmine import

Upvotes: 4

Related Questions