Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MouseEventConstructor is not a constructor

When I execute my tests locally they pass with no problems but when tests proceed on the server I get:

TypeError: MouseEventConstructor is not a constructor (evaluating 'new MouseEvent('mousedown',
EXEC : error : TypeError: MouseEventConstructor is not a constructor (evaluating 'new MouseEvent('mousedown', 
        {
            'which': 1,
            'view': window,
            'bubbles': true,
            'cancelable': true
        })')

for the code:

HTMLElement.prototype.mouseDownLeftButton = function () {
        var event = new MouseEvent('mousedown',
        {
            'which': 1,
            'view': window,
            'bubbles': true,
            'cancelable': true
        });
        this.dispatchEvent(event);
    };

which is totally fine. Is there any other way to create a new MouseEvent ?

like image 734
Yoda Avatar asked Jan 04 '23 07:01

Yoda


2 Answers

There is a polyfill from MDN that will resolve the issue:

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent#Polyfill

(function (window) {
    try {
        new MouseEvent('test');
        return false; // No need to polyfill
    } catch (e) {
        // Need to polyfill - fall through
    }

    // Polyfills DOM4 MouseEvent

    var MouseEvent = function (eventType, params) {
        params = params || { bubbles: false, cancelable: false };
        var mouseEvent = document.createEvent('MouseEvent');
        mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

        return mouseEvent;
    };

    MouseEvent.prototype = Event.prototype;

    window.MouseEvent = MouseEvent;
})(window);
like image 51
ErikAGriffin Avatar answered Jan 07 '23 10:01

ErikAGriffin


Most likely your local test infra uses real browser and on server it uses PhantomJS.

The latter still doesn't support new MouseEvent: https://github.com/ariya/phantomjs/issues/11289

I had to do the following trick to make tests pass:

    function createMouseEvent(typeArg: string): MouseEvent {
        let event = document.createEvent('MouseEvent');
        event.initMouseEvent(typeArg,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined);
        return event;
    }
like image 24
ZakiMa Avatar answered Jan 07 '23 11:01

ZakiMa