最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to mock a nativeElement.focus() in Angular 4 spec file - Stack Overflow

programmeradmin3浏览0评论

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'

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'

Share Improve this question edited Mar 20, 2018 at 19:45 risingTide 1,8969 gold badges38 silver badges65 bronze badges asked Feb 21, 2018 at 14:59 user1015388user1015388 1,5155 gold badges29 silver badges59 bronze badges 2
  • 1 anybody worked on this similar behavoiur – user1015388 Commented Feb 26, 2018 at 16:06
  • I'm having the same issue; if you e up with a resolution please post! – risingTide Commented Mar 20, 2018 at 14:22
Add a ment  | 

2 Answers 2

Reset to default 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 p: MyComponent;

    describe('myFunction', () => {

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

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

            p.myFunction();

            expect(p.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).

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;
  p.idNaicsRef = createSpyObj('idNaicsRef', ['nativeElement']);
  p.idNaicsRef.nativeElement = { focus: () => { }};

p is the reference to the ponent you are testing.

createSpyObj es from a jasmine import

发布评论

评论列表(0)

  1. 暂无评论