angular - 使用 cdkFocusInitial 运行材质对话框组件的开玩笑单元测试时,如何修复“[cdkFocusInitial]”不可聚焦警告?
问题描述
我正在对材质对话框组件运行开玩笑的单元测试,我cdkFocusInitial
在对话框中的输入元素上进行了测试。这在运行应用程序时非常有效,但是当我在 Jest 中运行单元测试时,我收到以下错误:
console.warn node_modules/@angular/cdk/bundles/cdk-a11y.umd.js:1861
Element matching '[cdkFocusInitial]' is not focusable. HTMLInputElement {
__zone_symbol__inputfalse: null,
__zone_symbol__blurfalse: null,
__zone_symbol__compositionstartfalse: null,
__zone_symbol__compositionendfalse: null,
__zone_symbol__focusfalse: null,
__zone_symbol__animationstartfalse: null,
[Symbol(SameObject caches)]: [Object: null prototype] { classList: DOMTokenList {} }
}
我试图在 stackblitz 中设置 jest 来重现,但我的组件本质上看起来与官方对话框示例非常相似。我在此处克隆了该示例,并添加了cdkFocusInitial
. 当您打开对话框时,焦点按预期设置:
我希望您能帮助找出我可以尝试修复/删除此警告的方法。
解决方法
在 beforeEach 函数中,我像这样模拟 console.warning:
beforeEach(() => {
// Removes "'[cdkFocusInitial]' is not focusable" warning when running tests
console.warn = jest.fn();
});
解决方案
您需要模拟InteractivityChecker
正在调用的服务isFocusable
。
最简单的方法是在您的 TestBed 中覆盖 isFocusable 方法,如下所示:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [...],
declarations: [...],
})
.overrideProvider(InteractivityChecker, {
useValue: {
isFocusable: () => true, // This checks focus trap, set it to true to avoid the warning
},
})
.compileComponents();
}));
推荐阅读
- logstash - 如何在 Terraform 模板中转义 Logstash sprintf 表达式?
- django - Django:身份验证表单仅在本地翻译?
- python - 是否有替代方法可以在内存中完全加载预训练的词嵌入?
- python - 使用请求包python时打开的文件太多
- java - Guice 检测未使用的绑定
- php - while 数组错误
- javascript - Redux/Thunk 中的递归函数返回 Promise 对象,而不是常规对象
- spring - WebLogic 12.2.1:使用 EAR 中的版本覆盖 common_modules 中的 Jackson 库
- sql - SQL:获取具有至少 N 个其他共同实体的实体对
- javascript - 如何使用自定义输入和变量构建 apollo 客户端突变