无法使用 Jest 测试 Stencil 应用程序的事件

Not able to test an event of Stencil app with Jest

我正在尝试测试源自 Stencil 组件中的图标 (<i>) 的点击事件。问题是我能够调试测试并且我看到测试在组件上触发了正确的方法,但是 Jest 无法 detect\register 事件并且 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 | });

默认情况下,自定义事件的名称是 属性 名称,在您的例子中是 tipInputEnterEvent。所以监听器应该是:

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

如果需要,您还可以更改活动名称:

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