gpt4 book ai didi

unit-testing - 使用 angular 和 jasmine 进行测试时如何模拟浏览器焦点?

转载 作者:太空狗 更新时间:2023-10-29 17:24:18 26 4
gpt4 key购买 nike

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

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() 调用实际上并没有被调用,但我不知道如何修复它。无论浏览器焦点如何,我编写的所有其他单元测试都通过了。有没有人遇到过这个或有任何想法?

最佳答案

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

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

实现同样目的的更优雅的方法是使用angular的wrapper方法:

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

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

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

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

注意:有些事件的运行方式与您预期的不同。例如,调度“点击”事件不会将焦点放在您的输入元素上!解决方法可能是首先触发“焦点”事件,然后触发“点击”事件,如下所示:

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

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

关于unit-testing - 使用 angular 和 jasmine 进行测试时如何模拟浏览器焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41992155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com