【问题标题】:Not able to test an event of Stencil app with Jest无法使用 Jest 测试 Stencil 应用程序的事件
【发布时间】:2022-02-09 17:17:31
【问题描述】:

我正在尝试测试源自 Stencil 组件中的图标 (<i>) 的点击事件。问题是我能够调试测试并且我看到测试在组件上触发了正确的方法,但是 Jest 无法检测\注册事件并且 toHaveBeenCalled() 方法失败。
input.spec.jsx

  it("dispatches icon click event", async () => {
    const page = await newSpecPage({
      components: [Input], //just the component name
      template: () => (<input-fields value="some input value"></input-fields>),
    });
  
    const eventSpy = jest.fn();
    page.win.addEventListener('input-field-search-event', eventSpy);

    await page.root.shadowRoot.querySelector('.icon-container').click();
    await page.waitForChanges();
    expect(eventSpy).toHaveBeenCalled();
  });


input.tsx

  private dispatchSearchEvent(e){
    //i can stop ay this point with a break point and the data passed by the test is correct
    this.tipInputEnterEvent.emit({type: "input-field-search-event", event: e, data: this.value});
  }

错误

  ● Input tests › dispatches icon click event

    expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

      334 |     await page.root.shadowRoot.querySelector('.icon-container').click();
      335 |     await page.waitForChanges();
    > 336 |     expect(eventSpy).toHaveBeenCalled();
          |                      ^
      337 |   });
      338 |
      339 | });

【问题讨论】:

    标签: jestjs stenciljs


    【解决方案1】:

    默认情况下,自定义事件的名称是属性名称,在您的情况下为 tipInputEnterEvent。所以听者应该是:

    page.win.addEventListener('tipInputEnterEvent', eventSpy);
    

    您也可以根据需要更改活动名称:

    @Event({ eventName: 'input-field-search-event' }) tipInputEnterEvent: EventEmitter;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-14
      • 2020-03-08
      • 2017-07-05
      • 2021-10-15
      • 2013-07-22
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多