7

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'

risingTide
  • 1,754
  • 7
  • 31
  • 60
user1015388
  • 1,283
  • 4
  • 25
  • 45

2 Answers2

7

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

risingTide
  • 1,754
  • 7
  • 31
  • 60
4

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

httpNick
  • 2,524
  • 1
  • 22
  • 34