Stencil version:
@stencil/core@1.7.0
Jest version:
"jest": "24.8.0"
Current behavior:
I am trying to focus a input element on button click.
Which works fine, however upon trying to test the functionality using npm test
, jest
throws a TypeError
saying focus is not a function.
This bug is being repeated for all the manual event invoke like click
, blur
, focus
.
Hence the test cases doesn't pass.
Expected behavior:
It should not throw error.
Steps to reproduce: I am providing a related demo code for inspection purpose. Related code:
demo-btn.tsx
import { Component, h, Element } from '@stencil/core';
@Component({
tag: 'demo-btn',
styleUrl: 'demo-btn.css',
shadow: true
})
export class DemoBtnComponent {
@Element() el!: HTMLElement;
private inputEl?: HTMLElement;
onClick = () => {
if (this.inputEl) {
this.inputEl.focus();
}
}
render() {
return (
<div class="input-container">
<input ref={el => this.inputEl = el} type="text" />
<button onClick={this.onClick}>
Click Me
</button>
</div>
);
}
}
demo-btn.spec.tsx
import { newSpecPage } from '@stencil/core/testing';
import { DemoBtnComponent } from './demo-btn';
describe('my-component', () => {
it('should focus input el on btn click', async ()=> {
const page = await newSpecPage({
components: [DemoBtnComponent],
html: '<demo-btn></demo-btn>',
});
const btn = page.root.shadowRoot.querySelector('button')
btn.click(); // Throws error after this line
await page.waitForChanges();
expect(true).toBeTruthy(); // For sake of completion
});
});
Any Help will be appreciated.
I Resolved this issue by mocking focus
of input element.
Below is the code I tried out:
import { newSpecPage } from '@stencil/core/testing';
import { DemoBtnComponent } from './demo-btn';
describe('my-component', () => {
it('should focus input el on btn click', async ()=> {
const page = await newSpecPage({
components: [DemoBtnComponent],
html: '<demo-btn></demo-btn>',
});
/** Mock Input Elements focus function */
const inputEl = page.root.querySelector('input');
inputEl.focus = jest.fn();
const btn = page.root.querySelector('button')
btn.click();
await page.waitForChanges();
expect(true).toBeTruthy();
});
});
Closing this issue.