开玩笑抛出TypeError:this.inputEl.focus不是函数#1964

时间:2019-10-21 05:53:18

标签: javascript jestjs stenciljs

模具版本:

 @stencil/core@1.7.0

最佳版本:

   "jest": "24.8.0"

当前行为:

我试图将输入元素集中在按钮单击上。 效果很好,但是在尝试使用npm test测试功能时,jest抛出TypeError,说明 focus不是功能。

对于所有手动事件调用,例如clickblurfocus,都会重复出现此错误。  因此,测试用例不会通过。

预期的行为:

它不应引发错误。

复制步骤: 我正在提供相关的演示代码以供检查。 相关代码:

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
  });
});

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我通过模拟输入元素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();
  });
});

解决此问题。