2

How can I simulate a mouse drag in a Typescript Unit test?

I know I can simulate a click with .click(), but I can't find a way to hold the click down instead of just an immediate click. I've tried to find a way to hold down a click, but can't find an option for this use case.

I want to test whether a certain area of the screen can be highlighted and selected, which requires a mouse drag.

Matt123
  • 556
  • 3
  • 15
  • 36
  • 1
    This is something you would do more on a e2e test and not a unit-test, however you can dispatch an event [mousedown](https://developer.mozilla.org/en-US/docs/Web/API/Element/mousedown_event) and a [mousedown](https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event) in order to "simulate" mouse button being pressed and dragged. Simply use the [dispatch](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent) API – Lucho Jun 11 '19 at 14:11

1 Answers1

5

I'm going to take a stab at this, and I'll continue to edit it, as I can find more info but hopefully this is a start.

The code is rough, but it should get you what you want, at least guide you to that point.

let fixture: ComponentFixture<TestComponent>;
let debugElement: DebugElement[];

beforeEach(() => {
    debugElement= fixture.debugElement.queryAll(By.component(TestComponent));
});

it('mousedown on the div', inject([MyService], service) => {
     debugElement[0].triggerEventHandler('mousedown',{pageX:50, pageY: 40});
     debugElement[0].triggerEventHandler('mousemove',{pageX:60, pageY: 50});
     expect(service.someObj).toBe({x:10, y:10});
});
Mark Hill
  • 1,769
  • 2
  • 18
  • 33
  • `debugElement[0].triggerEventHandler(...)` wasn't working for me with `mousemove` events, even though it worked for `mousedown` and `mouseup` events. I don't know why, but if anyone has the same problem, you can dispatch an event to the native element instead: `debugElement[0].nativeElement.dispatchEvent(new MouseEvent('mousemove', { pageX:60, pageY: 50}));` – lortimer Nov 13 '20 at 15:50