14

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();
    });
skyboyer
  • 22,209
  • 7
  • 57
  • 64
DauleDK
  • 3,313
  • 11
  • 55
  • 98
  • Hello. Have you found a solution for this? I face the same problem with Angular 9 and while running the tests with Karma and Jasmine. – Sergiu Aug 16 '20 at 04:02
  • Only the posted workaround, mocking the console.warn method – DauleDK Aug 17 '20 at 06:31

1 Answers1

14

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();
    }));
Yodacheese
  • 4,787
  • 5
  • 34
  • 42
  • Glad I can help! Had to do a bit of digging around the source code to find out where that error was triggering from – Yodacheese Feb 01 '21 at 20:18
  • 1
    Works great, for completeness; `InteractivityChecker` is imported from `@angular/cdk/a11y` since Intellij didn't suggest it for me. – Felix Apr 15 '22 at 06:46