https://stenciljs.com/docs/end-to-end-testing#set-a-prop-on-a-component-using-an-external-reference 提到它使用木偶戏中的
$eval
。但是当我检查测试浏览器时,我看不到分配给按钮的“单击”事件。
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>
);
}
}
这是我的测试用例
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();
});
显然你需要公开函数并做一些任何类型的事情。 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);
});