如何在 StencilJS 组件中测试事件

How to test event in StencilJS component

我有一个 StencilJS 组件,其事件定义为:

@Event({eventName: 'focusEvent'}) focusEvent: EventEmitter<any>;

组件如下所示:

<input type='text' 
    ... 
    onFocus={ (evt) => this.focusEvent.emit(evt)}>           
</input>

我的测试如下:

const mockEvent = jest.fn();
const page = await newE2EPage();
await page.setContent(`<my-textbox focusEvent=${mockEvent}></my-textbox>`);

await page.waitForSelector('input');
const el = await page.find('input');
expect(el).not.toBeNull();     // <-- this passes
       
const spy = el.spyOnEvent("focusEvent");
await el.focus();
expect(spy).toHaveBeenCalled();   // <-- this fails

错误是:

Matcher error: received value must be a mock or spy function

    Received has type:  object
    Received has value: {}

如果我将组件放入测试应用程序并 运行 它,我可以看到当我单击文本框时会触发焦点事件,但我不知道如何在一个测试。

尝试以下操作:

 const page = await newE2EPage();
 await page.setContent(`<my-textbox></my-textbox>`); // removed the focusEvent={...}
    
 const input = await page.find('input') // removed the waitForSelector + find, just find works 

 expect(input).not.toBeNull();     // <-- this passes

 const focusEventSpy = await page.spyOnEvent('focusEvent');

 await input.focus();

 await page.waitForChanges(); // introduced the wait for changes

 expect(focusEventSpy).toHaveReceivedEvent();   // <-- this now passes

要点:

  • waitForChanges,来自 stenciljs 文档:

Both Stencil and Puppeteer have an asynchronous architecture, which is a good thing for performance. Since all calls are async, it's required that await page.waitForChanges() is called when changes are made to components.