T
T
tostershmoster2021-09-29 08:45:42
Unit testing
tostershmoster, 2021-09-29 08:45:42

How to test method with event parameter: PointerEvent in jest?

method to be tested

private stopSliding(event: PointerEvent): void {
  const { pointerId } = event;
  const target = event.target as HTMLElement;
  target.onpointermove = null;
  target.releasePointerCapture(pointerId);
}


in the test I try to create a PointerEvent
test('', () => {
  const downEvent = new PointerEvent('pointerdown', {
      pointerId: 1,
      bubbles: true,
      cancelable: true,
      clientX: 150,
      clientY: 150,
      pointerType: 'touch',
      width: 20,
      height: 20,
      preassure: 0,
      tangentialPressure: 0,
      tiltX: 0,
      tiltY: 0,
      isPrimary: true,
  });

  const view = new View('range-slider', settings);
  view.from.element.dispatchEvent(downEvent);
  const result = view['stopSliding'](downEvent);
});


Upd:
added to setupEvent.js
global.PointerEvent = function (type, eventInitDict) {};
global.BeforeUnloadEvent = function () {};

and in jest.config.js
module.exports = {
  setupFilesAfterEnv: ['./path/setupEvents'],
};


got an error
TypeError: Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.
|     view.from.element.dispatchEvent(downEvent);


Upd:
added polyfill
export class PointerEvent extends MouseEvent {
  public height?: number;
  public isPrimary?: boolean;
  public pointerId?: number;
  public pointerType?: string;
  public pressure?: number;
  public tangentialPressure?: number;
  public tiltX?: number;
  public tiltY?: number;
  public twist?: number;
  public width?: number;

  constructor(type: string, params: PointerEventInit = {}) {
    super(type, params);
    this.pointerId = params.pointerId;
    this.width = params.width;
    this.height = params.height;
    this.pressure = params.pressure;
    this.tangentialPressure = params.tangentialPressure;
    this.tiltX = params.tiltX;
    this.tiltY = params.tiltY;
    this.pointerType = params.pointerType;
    this.isPrimary = params.isPrimary;
  }
  public ReleasePointerCapture(value);
}
global.PointerEvent = PointerEvent as any;


got error
TypeError: target.releasePointerCapture is not a function
61567de717126704733910.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Loli E1ON, 2021-09-29
@tostershmoster

https://github.com/kulshekhar/ts-jest/issues/1035#...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question