Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fix the '[cdkFocusInitial]' is not focusable warning, when running jest unit test of a material dialog component with cdkFocusInitial?

I am running jest unit test of a material dialog component, where I have cdkFocusInitial on an input element in the dialog. This works perfect when running the application, but when I run unit tests in Jest I get the following error:

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 {} }
    }

I tried to setup jest in stackblitz to reproduce, but my component essentially look very similar to the official dialog example. I have cloned that example here, and added cdkFocusInitial. When you open the dialog, focus is set as expected:

enter image description here

I hope you can help figure out what I can try to fix/remove this warning.

Workaround

In a beforeEach function, I mock the console.warning like this:

 beforeEach(() => {
       // Removes "'[cdkFocusInitial]' is not focusable" warning when running tests
       console.warn = jest.fn();
    });
like image 778
DauleDK Avatar asked Nov 15 '19 15:11

DauleDK


1 Answers

You'll need to mock the InteractivityChecker service which is what is calling isFocusable.

Easiest way to do this is in your TestBed override the isFocusable method like the following:

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [...],
            declarations: [...],
        })
            .overrideProvider(InteractivityChecker, {
                useValue: {
                    isFocusable: () => true, // This checks focus trap, set it to true to  avoid the warning
                },
            })
            .compileComponents();
    }));
like image 136
Yodacheese Avatar answered Sep 18 '22 14:09

Yodacheese