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

风格不统一 提交于 2021-01-27 07:10:56

问题


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'


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/48909043/how-to-mock-a-nativeelement-focus-in-angular-4-spec-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!