我正在尝试使用 Cypress 测试框架在 React Web 应用程序上的输入类型编号上模拟鼠标滚轮事件。我按照他们的文档( https://docs.cypress.io/api/commands/trigger.html )使用 trigger
但似乎网上关于如何实际创建合成事件及其需要哪些参数的信息很少。这是我到目前为止所拥有的:
cy.get("#cost-amount-input")
.click()
.trigger("mouseover")
//.trigger("mousewheel", {deltaY: 99})
.trigger("wheel", { deltaY: -66.666666, wheelDelta: 120, wheelDeltaX: 0, wheelDeltaY: 120, bubbles: true})
.blur()
.then(() => {
/* test if the mouse wheel event chagned the value as expected */
});
向文档中添加所有滚轮事件的事件监听器显示我的事件正在触发,但它不会导致值发生变化,就像我执行实际的鼠标滚轮事件时发生的那样。这是我的事件监听器捕获的两个不同的事件。 Cypress合成事件(不起作用)
实际的鼠标滚轮事件(确实有效 - 更改值):
任何信息都值得赞赏。
最佳答案
按照此处的示例 MDN - Creating and triggering events ,我构建了一个最小的示例来重现该问题。
<body>
<input type="number" />
<script>
const event = new Event('wheel');
const elem = document.querySelector('input');
elem.addEventListener('wheel', function (e) {
elem.value = +elem.value + 1; // treat input value as a number
}, false);
elem.dispatchEvent(event); // dispatch an event to show it's working
</script>
</body>
这是测试(通过)。
it('Cypress "trigger" fires synthetic event', () => {
cy.visit('../app/synthetic-event.html');
cy.get('input').invoke('val').should('eq', '1'); // input has '1' since event triggered on load
cy.get('input').trigger("wheel"); // trigger the synthetic event
cy.get('input').invoke('val').should('eq', '2'); // confirm value has changed
})
我能看到的唯一实际差异是您的“实际鼠标滚轮事件”日志显示负 wheelDelta
和正 deltaY
,而您的测试显示<强>相反极性。
也许输入不允许相反方向的变化(即负输入)?
请分享事件构造函数和事件监听器的代码。
关于javascript - 使用 Cypress 模拟输入类型数字上的合成鼠标滚轮事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65932621/