【问题标题】:How do I check if my element has been focused in a unit test in angular 4?如何检查我的元素是否已集中在角度 4 的单元测试中?
【发布时间】:2017-06-22 09:53:12
【问题描述】:

我有以下功能进行单元测试。我在组件中采用了带有视图子元素的文本框元素,在测试中我需要测试在调用setTimeout() 之后我的文本框是否获得焦点。

 @ViewChild('searchInput') searchInput: ElementRef;
function A(show) {
        const self = this;
        if (show) {
            this.xyz= true;
            setTimeout(function () {
                self.searchInput.nativeElement.focus();
            }, 0);
        } else {
            self.xyz= false;
            self.abc = '';
        }
    }

这是我正在尝试的测试用例:

it('textbox get focus toggleSearch', async(() => {
        let el: DebugElement;

        component.toggleSearch(true);
        el = fixture.debugElement.query(By.css('#search-input-theme'));
        let native: HTMLElement = el.nativeElement;
        spyOn(native,'focus');
        fixture.whenStable().then(() => {
            expect(native.focus).toHaveBeenCalled();
        });
    }));

【问题讨论】:

    标签: angular angular2-testing


    【解决方案1】:

    可能是这样的:

    const input = de.query(By.css("your_field_selector")).nativeElement;
    const focusElement = de.query(By.css(":focus")).nativeElement;
    expect(focusElement).toBe(input);
    

    路易斯

    【讨论】:

      【解决方案2】:

      Luis Abreu 的回答对我有用,因为我不仅想监视焦点方法被调用,而且焦点设置在视图上的正确元素上。这是一个例子:

      describe('Email input focus', () => {
        beforeEach(() => {
          spyOn(comp.emailField.nativeElement, 'focus');
          comp.ngAfterViewInit();
        });
      
        it('Should call the focus event', () => {
          expect(comp.emailField.nativeElement.focus).toHaveBeenCalled();
        });
      
        it('Should be focused on the view', () => {
          fixture.detectChanges();
          const emailInput = de.query(By.css('#email')).nativeElement;
          const focusedElement = de.query(By.css(':focus')).nativeElement;
          expect(focusedElement).toBe(emailInput);
        });
      });
      

      【讨论】:

        【解决方案3】:

        您可以直接查询原生元素并使用唯一的选择器

        const input = fixture.nativeElement.querySelector('#your-input-id:focus');
        expect(input).toBeTruthy();
        

        【讨论】:

        • 这似乎只有在浏览器窗口也有焦点的情况下才有效,所以它最终有点不稳定。
        • 忽略 jasmine 中的焦点问题的解决方法:const focused = () => fixture.nativeElement.querySelector(':focus'); button.nativeElement.focus(); if (focused() !== button.nativeElement) { pending('Requires browser focus'); return; }
        猜你喜欢
        • 2017-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 2013-05-29
        • 2014-09-07
        相关资源
        最近更新 更多