angular - 使用cdkFocusInitial对 Material 对话框组件进行 Jest 单元测试时,如何解决 '[cdkFocusInitial]'不能聚焦的警告?

标签 angular jestjs angular-cdk

我正在对 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。当您打开对话框时,焦点将按预期设置:

enter image description here

希望您能帮助我找出可以解决/删除此警告的方法。

解决方法

在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/

相关文章:

javascript - Angular 6 - 服务中的 API 后调用 - 更改为使用 XML

angular - 如何从日期数组中禁用 Angular Material Datepicker 日期?

javascript - JavaScript React 项目中的高 Jest 堆内存使用率

angular - cdkStepLabel - ng-模板 - innerHTML

angular - 如何在 Angular 7 中禁用 objective-c dkDropList 中的元素移位/移动

Angular Material 2 Table Mat Row Click 事件也通过在 Mat Cell 中单击按钮来调用

angular - Angular DOM 中的 StaticInjectorError

javascript - mustache 式数据绑定(bind)的通用名称是什么?

unit-testing - 在CDK测试中,toHaveResource和toHaveResourceLike有什么区别?

reactjs - setupTests.js 未在 CRA React 应用程序中自动加载