如何使用 Jest 在 Stencil 中测试 LifeCycles 和 EvenEmitters
How to test LifeCycles and EvenEmitters in Stencil with Jest
我正在使用 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
由于 Stencil 正在实例化您的 EventEmitter,我建议使用 end-to-end testing 使用 newE2EPage
:
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();
});
我正在使用 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
由于 Stencil 正在实例化您的 EventEmitter,我建议使用 end-to-end testing 使用 newE2EPage
:
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();
});