当使用cdkFocusInitial对材质对话框组件运行jest单元测试时,如何修复“[cdkFocusInitial]”不可聚焦警告?

icnyk63a  于 2023-09-28  发布在  Jest
关注(0)|答案(2)|浏览(131)

我正在运行一个材质对话框组件的jest单元测试,其中我在对话框中的输入元素上有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();
    });
rsl1atfo

rsl1atfo1#

您需要模拟调用isFocusableInteractivityChecker服务。
最简单的方法是在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();
    }));
2ekbmq32

2ekbmq322#

使用**Spectator**时。您需要从@angular/cdk/a11y包中模拟InteractivityChecker

import { createHostFactory } from '@ngneat/spectator/jest';
import { InteractivityChecker } from '@angular/cdk/a11y';

const createHost = createComponentFactory({
  ...
  providers: [
    {
      provide: InteractivityChecker,
      useValue: {
        isFocusable: () => true,
      },
    },
  ],
  ...
});

相关问题