Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 646
user1015388 Avatar asked Feb 21 '18 14:02

user1015388


2 Answers

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).

like image 189
risingTide Avatar answered Nov 01 '22 12:11

risingTide


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

like image 29
httpNick Avatar answered Nov 01 '22 13:11

httpNick