javascript - 开玩笑抛出 TypeError : this.inputEl.focus 不是函数 #1964
问题描述
模板版本:
@stencil/core@1.7.0
开玩笑版:
"jest": "24.8.0"
当前行为:
我正在尝试将输入元素集中在按钮单击上。效果很好,但是在尝试使用 测试功能npm test
时,jest
会抛出一个TypeError
说法,焦点不是功能。
click
对于所有手动事件调用,如、blur
、 ,都会重复此错误focus
。因此测试用例没有通过。
预期行为:
它不应该抛出错误。
重现步骤: 我提供了一个相关的演示代码以供检查。 相关代码:
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
});
});
任何帮助将不胜感激。
解决方案
focus
我通过模拟输入元素解决了这个问题。以下是我尝试过的代码:
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();
});
});
关闭这个问题。
推荐阅读
- python - 为什么 asyncio.iscoroutine 在生成器上返回 True?
- smtp - 使用 GSuite SMTP 发送邮件失败
- r - 更改 R 中的时区而不返回原始时区
- android - Android - 将正文添加到 StringRequest 时来自 Flask 的 Volley 错误 400
- javascript - React 组件返回 jsx 以外的内容
- java - java 控制台不会随着我的源代码中的更改而更新
- algorithm - 循环块内包含循环的 else 块的复杂性
- vba - 如何让 Selection.Text 读取宏域代码的显示文本
- c - 快速位连接反转参数之一
- python - 将键与字典中的值匹配