【问题标题】:How can i simulate browser focus when testing using angular and jasmine?使用 Angular 和 jasmine 进行测试时如何模拟浏览器焦点?
【发布时间】:2017-06-18 22:19:58
【问题描述】:

我正在尝试编写一个单元测试来检查焦点事件的影响是否发生。我的实际测试用例更复杂,但我使用以下代码创建了一个最小复制:

it('testing input focus', async(() => {
  let showDiv = false;
  const template = `<div *ngIf="shouldShow" class='hidden-div'>
                       SHOW ME WHAT YOU GOT
                    </div>
                    <input (focus)="shouldShow = !shouldShow" name="input">`;
  buildTestComponent(template, {shouldShow: showDiv}).then((fixture) => {
    fixture.detectChanges();
    const inputEl: HTMLInputElement = fixture.nativeElement.querySelector('input');

    expect(fixture.nativeElement.querySelector('.hidden-div')).toBe(null);

    inputEl.focus();
    fixture.detectChanges();

    expect(fixture.nativeElement.querySelector('.hidden-div')).not.toBe(null);
  });
}));

当我使用 karma 运行此测试时,只要我专注于运行 karma 目标的 chrome 选项卡,测试就会通过。但是,如果浏览器没有焦点,则测试失败(即使浏览器可见,但我单击另一个窗口)并显示错误消息:

Expected null not to be null.

我假设当 Chrome 选项卡没有焦点时, inputEl.focus() 调用实际上并没有被调用,但我不知道如何修复它。无论浏览器焦点如何,我编写的所有其他单元测试都通过了。有没有人遇到过这个或者有什么想法?

【问题讨论】:

  • 今天遇到了同样的问题。不确定修复它的最优雅的方法是什么。

标签: unit-testing angular jasmine karma-jasmine


【解决方案1】:

要在 Angular 元素上触发事件,您可以使用内置的 JavaScript ES6 方法 dispatchEvent 并随后调用 Angular 的更改检测机制来更新您的 DOM:

inputElement.dispatchEvent(new Event('focus'));
fixture.detectChanges();

实现相同目的的更优雅的方法是使用 angular 的包装器方法:

import { dispatchEvent } from '@angular/platform-browser/testing/src/browser_util'

dispatchEvent(inputElement, 'focus');
fixture.detectChanges();

一个有趣的例子是当你想为你的输入元素设置一个值。您需要先为输入的 value 属性分配一个字符串,然后触发“输入”更改事件:

inputElement.value = 'abcd';
dispatchEvent(inputElement, 'input');
fixture.detectChanges();

注意:有些事件并不像您预期​​的那样发生。例如,调度一个 'click' 事件不会将焦点放在您的输入元素上!一种解决方法可能是先触发“焦点”事件,然后触发“点击”事件,如下所示:

dispatchEvent(inputElement, 'focus');
dispatchEvent(inputElement, 'input');
fixture.detectChanges();

所有可用的 JavaScript 事件都是here。

【讨论】:

  • import { dispatchEvent } from '@angular/platform-browser/testing/src/browser_util' => 依赖不存在。
  • 这个答案很有帮助,当 inputElement.focus() 之类的东西不起作用时救了我。
猜你喜欢
  • 2020-03-05
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
相关资源
最近更新 更多