gpt4 book ai didi

javascript - 如何使用纯 JavaScript 在 grunt-run qunit 测试中触发 TouchEvent?

转载 作者:行者123 更新时间:2023-12-03 12:38:57 24 4
gpt4 key购买 nike

我有我想测试的各种触摸事件的回调。例如,“touchstart”事件使用触摸的坐标来设置我的类的成员:

NavigationUI.prototype.touchStart = function(evt) {
this.interacting = true;
this.startPoint = this.getTouchXY(evt);
};
NavigationUI.prototype.getTouchXY = function(evt) {
var rect = this.element.getBoundingClientRect();
return {
x: evt.targetTouches[0].clientX - rect.left,
y: evt.targetTouches[0].clientY - rect.top
};
};

我没有使用 jQuery。为了测试这个函数,我需要在已知位置创建一个 div,创建一个 Touch 事件来正确设置第一个 targetTouches Touch 的 clientX 和 clientY 变量,然后触发该事件并检查回调是否执行了它应该执行的操作。我对鼠标事件有类似的回调。示例测试是:

test('test mouseDownCallback', function() {                                   
var div, evt, navElement;
div = document.createElement('div');
div.setAttribute('style', 'position: fixed; left: 0px; top: 0px;');
document.body.appendChild(div);
navElement = new lasertutor.NavigationUI(div);
evt = document.createEvent("MouseEvent");
evt.initMouseEvent("mousedown", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
div.dispatchEvent(evt);
ok(navElement.interacting, "mousedown doesn't set interacting");
return deepEqual({
x: 0,
y: 0
}, navElement.startPoint);
});

但是,似乎没有文档可以尝试对触摸事件执行此操作。好像有a description of the Touch Event Interface无法触发,an Apple Developer page on the initTouchEvent function没有提及任何构建所需 Touch 或 TouchList 参数的方法,并且 another SO question从 2011 年开始,不包括使用任何位置数据填充触摸事件。

我当前的测试如下所示,并使用 Apple Dev 页面中的 initTouchEvent 规范,并尝试简单地模拟 TouchList 和 Touch 对象:

test("test TouchStartCallback", function() {                                  
var div, evt, navElement, touch1;
div = document.createElement('div');
div.setAttribute('style', 'position: fixed; left: 0px; top: 0px;');
document.body.appendChild(div);
navElement = new lasertutor.NavigationUI(div);
evt = document.createEvent("TouchEvent");
touch1 = document.createTouch({
clientX: 0,
clientY: 0,
id: 0,
pageX: 0,
pageY: 0,
screenX: 0,
screenY: 0,
target: div
});
evt.initTouchEvent("touchstart", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, [touch1], [touch1], [touch1], 1, 0);
div.dispatchEvent(evt);
ok(navElement.interacting, "touchstart doesn't set interacting");
return deepEqual({
x: 0,
y: 0
}, navElement.startPoint);
});

我将此测试作为 grunt Qunit 任务的一部分运行。它失败了,没有错误,表明 ok 和 deepEqual 断言都不正确。此测试的 mouseEvent 版本通过了。

最佳答案

您是否正确使用 document.createTouch ?根据Safari developer您需要传递事件发生的 View (窗口)。

createTouch( DOMWindow View 、EventTarget 目标、长标识符、长 pageX、长 pageY、长 screenX、长 screenY)

touch1 = document.createTouch(window, div, 1, 0, 0, 0, 0);

关于javascript - 如何使用纯 JavaScript 在 grunt-run qunit 测试中触发 TouchEvent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23597493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com