Imran Khan
Imran Khan

Reputation: 153

How to test LifeCycles and EvenEmitters in Stencil with Jest

I am using Stenciljs and Jest. I am having a hard time testing events triggered in the lifecycle (componentDidLoad).

I am able to enter the lifecycle, but unable to test the .emit() event.

I have tried the following:

.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();
 });

Here is the situation at a glance:

.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();
  });

The (logical) following error occurs:

● render component › should spyOn componentDidLoad

TypeError: Cannot read property 'emit' of undefined

Upvotes: 1

Views: 3213

Answers (1)

matthewsteele
matthewsteele

Reputation: 1872

Since Stencil is instantiating your EventEmitter I would recommend using end-to-end testing using 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();
    });

Upvotes: 2

Related Questions