Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.click() not working in mocha-phantomjs on certain elements

I am writing some tests using the Mocha test framework and Chai assertions library I've been testing these in a chrome browser and they work fine, but then I try them in the headless browser mocha-phantomjs and the .click() events I am sending on certain elements just dont seem to be firing, while others are working.

The test successfully logs in to the website, which is done using:

$("#login").click()

"#login" is a form submit button and it works fine using click this way.

Next I want to click on a menu item which is an anchor element.

$("#menuItemToClick").click();

This is where it stops working in mocha-phantomjs even though this works fine within chrome.

So obviously the .click() function is defined and working but not for this element.

I've exhausted my google-foo. Here are some of the other things I have seen others mention and tried:

Use javascript dispatchEvent

var evObj = new CustomEvent('click');
evObj.initEvent('click', true, false);
document.getElementById('menuItemToClick').dispatchEvent(evObj);

This does fire the click event and takes the browser to the right url but it also causes the whole page to reload, in both chrome and mocha-phantomjs, which restarts the tests from the beginning putting them in a infinite loop... Is there a way to use this without it causing a page reload?

Use phantomjs' page.sendEvent()

var elementPosition = $("#menuItemToClick").offset();
page.sendEvent('click', elementPosition.left + 1, elementPosition.top + 1);

This is supposed to send a native click event if you pass it the correct co-ordinates of the element. I tried to get this to work but I couldn't seem to access the page from within the mocha tests that are running. Is there a way to access the phantomjs page variable from within the mocha-phantomjs tests?

Any help is greatly appreciated!

like image 848
Dsyko Avatar asked May 28 '13 22:05

Dsyko


1 Answers

I went back and played with this for a while more and finally got the dispatchEvent to work without resetting the page and it works in both chrome and mocha-phantomjs! I think the page reset/reload had something to do with the event not being a mouse event specifically.

I placed a convenience function at the top of my tests:

var clickElement = function (el){
    var ev = document.createEvent("MouseEvent");
    ev.initMouseEvent(
      "click",
      true /* bubble */, true /* cancelable */,
      window, null,
      0, 0, 0, 0, /* coordinates */
      false, false, false, false, /* modifier keys */
      0 /*left*/, null
    );
    el.dispatchEvent(ev);
};

and can now click my anchor element:

clickElement($("#menuItemToClick")[0]);
like image 157
Dsyko Avatar answered Oct 29 '22 21:10

Dsyko