首页 > 解决方案 > 使用 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();
    });

标签: angularjestjsangular-cdk

解决方案


您需要模拟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();
    }));

推荐阅读