模板无法使用 Jest 测试 mouseenter\mouseleave 事件
我使用 Stencil 构建了一个简单的按钮组件,并分配了 4 个事件(onMouseDown
、onMouseUp
、onMouseEnter
、onMouseLeave
)按钮。该组件如下所示:
.
.
.
@State() buttonState: string ='disabled';
.
.
.
someInternalLogic(eventName: Events) {
...//just sets a state variable of this.buttonState
}
render() {
return (
<button
onMouseDown={() => this.someInternalLogic(Events.MOUSEDOWN)}
onMouseUp={() => this.someInternalLogic(Events.MOUSEUP)}
onMouseEnter={() => this.someInternalLogic(Events.MOUSEENTER)}
onMouseLeave={() => this.someInternalLogic(Events.MOUSELEAVE)}
>
</button>
);
}
我对一般测试尤其是 Jest
不太熟悉。我很难理解如何综合测试这些事件。我想出了一个可行的解决方法,但显然不是可行的方法。
解决方法:
it('should mouseleave', async () => {
const button = await page.root.shadowRoot.querySelector('button');
const mouseleave = new window.Event("mouseleave", {
bubbles: false,
cancelable: false
});
let mouseleaveBool = false;
button.addEventListener("mouseleave", e=>{
mouseleaveBool = true;
});
await button.dispatchEvent(mouseleave);
await page.waitForChanges();
expect(mouseleaveBool ).toBeTruthy();
});
I built a simple button component using Stencil and assigned 4 events (onMouseDown
, onMouseUp
onMouseEnter
, onMouseLeave
), to the button. The component looks like this:
.
.
.
@State() buttonState: string ='disabled';
.
.
.
someInternalLogic(eventName: Events) {
...//just sets a state variable of this.buttonState
}
render() {
return (
<button
onMouseDown={() => this.someInternalLogic(Events.MOUSEDOWN)}
onMouseUp={() => this.someInternalLogic(Events.MOUSEUP)}
onMouseEnter={() => this.someInternalLogic(Events.MOUSEENTER)}
onMouseLeave={() => this.someInternalLogic(Events.MOUSELEAVE)}
>
</button>
);
}
I'm new to testing in general and Jest
in particular. I'm having troubles understanding how to test these events synthetically. I've come up with a workaround which works, but is obviously not the way to go.
The workaround:
it('should mouseleave', async () => {
const button = await page.root.shadowRoot.querySelector('button');
const mouseleave = new window.Event("mouseleave", {
bubbles: false,
cancelable: false
});
let mouseleaveBool = false;
button.addEventListener("mouseleave", e=>{
mouseleaveBool = true;
});
await button.dispatchEvent(mouseleave);
await page.waitForChanges();
expect(mouseleaveBool ).toBeTruthy();
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您可以直接在组件实例上调用事件处理程序,而不是调度事件
因此对于此组件
测试可以如下所示
Instead of dispatching events you can directly call event handlers on your component instance
So for this component
Test can look like this