wasilikoslow
wasilikoslow

Reputation: 1973

How to pass function as prop in stenciljs e2e tests?

https://stenciljs.com/docs/end-to-end-testing#set-a-prop-on-a-component-using-an-external-reference its mentioned as using $evalfrom puppetry. But when I inspect the testing browser I cant see the "click" event assigned to the button.

import { Component, h, Host, Prop } from '@stencil/core';
 

@Component({
  tag: 'custom-button', 
  shadow: true,
})
export class CustomButton {
  @Prop() onClick!: (event: UIEvent) => void;

  render() {
    return (
      <Host>
        <button
          onClick={this.onClick} 
        >
          <slot />
        </button>
      </Host>
    );
  }
}

and here is my test case

it('should render the button and click ', async () => {
    const props = {
    onClick: jest.fn(),
    };
    const page = await newE2EPage({
      waitUntil: 'networkidle2',
    }); 
    await page.setViewport({ width: 400, height: 800 });
    await page.setContent('<custom-button>some text</custom-button>');
    await page.$eval(
      'custom-button',
      (elm, { onClick }) => {
        elm.onClick = onClick;
      },
      props,
    );
 

    const customButton = await page.find('custom-button');
    customButton.setProperty('onClick', props.onClick);
    expect(customButton).not.toBeFalsy();

    const buttonElement = await page.find('custom-button >>> button');
    buttonElement.triggerEvent('onClick');
    console.log('buttonElement ', buttonElement.triggerEvent('onClick'));
    await buttonElement?.click();
    await page.waitForChanges();

    expect(props.onClick).toHaveBeenCalled();
  });

Upvotes: 0

Views: 50

Answers (1)

wasilikoslow
wasilikoslow

Reputation: 1973

Apparently you need to expose the function and do some typing to "this". https://github.com/ionic-team/stencil/issues/1174

it('should render the button and click ', async () => {
    const page = await newE2EPage({
      waitUntil: 'networkidle2',
    });
    await page.setViewport({ width: 400, height: 800 });
    await page.setContent('<custom-button>some text</custom-button>');
    const onClick = jest.fn();
    await page.exposeFunction('onClick', onClick);
    await page.$eval(
      'custom-button',
      (elm, { onClick }) => {
        elm.disabled = false;
        elm.onClick = (this as any).onClick;
      },
      props,
    );
    await page.waitForSelector('.hydrated');

    const customButton = await page.find('custom-button');
    await customButton?.click();
    customButton.setProperty('onClick', props.onClick);
    await page.waitForChanges();
    expect(customButton).not.toBeFalsy();

    const buttonElement = await page.find('custom-button >>> button');

    await buttonElement?.click();
    await page.waitForChanges();

    expect(onClick).toHaveBeenCalled();
    expect(onClick).toHaveBeenCalledTimes(1);
  });

Upvotes: 0

Related Questions