我有一个StencilJS组件,它的Event定义为:
@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
, from stenciljs docs:
Stencil和Puppeteer都有异步架构,即这对性能来说是件好事。因为所有的调用都是异步的,所以它是必需的当发生更改时,会调用page.waitForChanges()组件。
- 查找方法的使用(Stencil#FindElementsInDOM, Stencil#FindElementsInShadowDOM)