我正在尝试编写一个单元测试,检查焦点事件的效果是否发生。我的实际测试情况是比较复杂的,但我已经创建了一个最小的再现与下面的代码:Angular 2 + Jasmine:测试焦点时的浏览器焦点
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);
});
}));
当我运行该测试业力测试通过了,只要我有焦点的Chrome标签页上运行业力目标。但是,如果浏览器不具有焦点测试失败(即使浏览器是可见的,但我点击另一个窗口),并显示错误消息:
Expected null not to be null.
我认为当Chrome标签没有焦点,inputEl.focus()调用实际上并没有被调用,但我不知道如何解决它。无论浏览器焦点如何,我写过的所有其他单元测试都通过有没有人遇到这个或有任何想法?
今天遇到同样的问题。不知道修复它的最优雅的方法是什么。 – DevVersion