我正在使用Stenciljs和Jest。 我很难测试生命周期中触发的事件(componentDidLoad)。
我能够进入生命周期,但是无法测试.emit()事件。
我尝试了以下方法:
.spec.ts
it('should spyOn componentDidLoad', () => {
const component = new App();
jest.spyOn(component, 'componentDidLoad');
let eventSpy = jest.fn();
component.document.addEventListener('toScroll', eventSpy);
expect(component.componentDidLoad()).toHaveBeenCalled();
});
这里情况一目了然
.tsx
@Event() toScroll: EventEmitter<void>;
componentDidLoad() {
this.toScroll.emit();
}
.spec.ts
it('should spyOn componentDidLoad', () => {
const component = new App();
jest.spyOn(component, 'componentDidLoad');
// need a way to test the emit() here.
expect(component.componentDidLoad()).toHaveBeenCalled();
});
发生以下(逻辑)错误:
●渲染组件›应该spyOn componentDidLoad
TypeError: Cannot read property 'emit' of undefined
答案 0 :(得分:1)
由于模板正在实例化您的EventEmitter,所以我建议使用newE2EPage
使用end-to-end testing:
import { newE2EPage } from '@stencil/core/testing';
it('should emit an event on load', async () => {
const page = await newE2EPage();
await page.setContent(`
<my-app></my-app>
`);
const toScroll = await page.spyOnEvent('toScroll');
await page.waitForChanges();
expect(toScroll).toHaveReceivedEvent();
});