我正在对 Material 对话框组件进行开玩笑的单元测试,在对话框的输入元素上有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以进行复制,但是我的组件本质上看起来与官方对话框示例非常相似。我已经克隆了example here,并添加了
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();
}));
关于angular - 使用cdkFocusInitial对 Material 对话框组件进行 Jest 单元测试时,如何解决 '[cdkFocusInitial]'不能聚焦的警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58879736/