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:
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();
});
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();
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With