它们大致提供了如何制作拖动物的示例.
我的问题是你如何测试他们的例子/实施:
var startX = 0,startY = 0; scope.x = 0; scope.y = 0; element.css({ top: scope.y,left: scope.x }); element.on('mousedown',function(event) { // Prevent default dragging of selected content event.preventDefault(); startX = event.pageX - scope.x; startY = event.pageY - scope.y; $document.on('mousemove',mousemove); $document.on('mouseup',mouseup); }); function mousemove(event) { scope.y = event.pageY - startY; scope.x = event.pageX - startX; element.css({ top: scope.y + 'px',left: scope.x + 'px' }); } function mouseup() { $document.off('mousemove',mousemove); $document.off('mouseup',mouseup); } }
但这只适用于单个事件.
Angular的示例使用mousedown添加mousemove和mouseup事件侦听器,this stackoverflow answer使用triggerHandler–它可以防止冒泡/传播.
现在我(大致):
describe('on mousedown it',function(){ it('moves a thing',function(){ expect(scope.x).toBe(0); element.triggerHandler({type: 'mousedown',pageX: 0,pageY:0}); element.triggerHandler({type: 'mousemove',pageX:10,pageY:10); expect(scope.x).toBe(10); }); });
测试失败了. scope.x记录为0.
做什么?
鉴于我们有一个名为myDraggable的指令,它的应用如此< span my-draggable =“”> Drag Me< / span>,在测试时:
>让我们编译指令.
var scope = $rootScope.$new();
var elem = $compile(‘< span my-draggable =“”> Drag Me< / span>‘)(范围);
>然后将鼠标按下事件发送到编译元素
elem.triggerHandler({type:’mousedown’,pageX:0,pageY:0});
>之后,因为鼠标移动事件附加到$document,让鼠标移动事件发送到$document
$document.triggerHandler({type:’mousemove’,pageX:10,pageY:20});
>最后,让我们断言编译元素的最终位置
期待(elem.css( ‘顶’)).TOBE( ’20像素’)
期待(elem.css( ‘左’)).TOBE( ’10px的’)
当我们把它们放在一起时,
describe('on mousedown it',function(){ beforeEach(module('dragModule')); it('moves a thing',inject(function($compile,$rootScope,$document){ var scope = $rootScope.$new(); var elem = $compile('<span my-draggable="">Drag Me</span>')(scope); $rootScope.$digest(); elem.triggerHandler({type: 'mousedown',pageY:0}); $document.triggerHandler({type: 'mousemove',pageX: 10,pageY:20}); expect(elem.css('top')).toBe('20px'); expect(elem.css('left')).toBe('10px'); })); });
这是关于测试指令的推荐方法的官方角度文档:https://docs.angularjs.org/guide/unit-testing#testing-directives
这是实施我刚刚谈到的所有内容的plunker:https://plnkr.co/edit/QgWiVlbNOKkhn6wkGxUK?p=preview