如何定义与被触发事件相关的测试功能

时间:2014-01-11 03:37:14

标签: qunit

js file

window.onload = function() {
    document.getElementById('example').addEventListener('mousedown', myFunction, false);
};

function myFunction(e) {
    x = e.clientX-parseInt(document.getElementById('example').offsetLeft);
    window.addEventListener('mousemove', anotherFunction, true);
}

试图找出如何使用QUnit进行测试。该页面不使用jQuery,只是直接使用JavaScsript。如您所见,onload包含一个添加到元素的eventlistener,当触发该鼠标事件时,将调用myFunction函数。 qunit code please。

1 个答案:

答案 0 :(得分:0)

在我看来,这应该是两个测试:

一:您要测试以确保正确附加事件侦听器。为此,您可以覆盖myFunction(或使用来自sinon的间谍)。然后触发鼠标单击(请参阅MDN for triggering events)。

然后对于下一个函数,同样只附加间谍或覆盖anotherFunction,然后直接调用你的方法。

**编辑关于SPIES的信息**

如果您已经加载了sinon,并且myFunction在范围内可用,则会使myFunction成为间谍。

From the docs for spiesevent triggering

test('callback', function(){
    sinon.spy(myFunction);
    // or
    var oldFunc = myFunction;
    myFunction = function(){
        ok(true, true, 'function called');
    }
    var event = new MouseEvent('down', {
        'view': window,
        'bubbles': true,
        'cancelable': true
     });

    // trigger event 
    document.getElementById('example').dispatchEvent(event);

    ok(myFunction.called, true, 'function called');
    myFunction.restore();
    //or
    myFunction = oldFunc;
});
相关问题