calling click() function on html element in jasmin

2019-08-12 07:56发布

问题:

This question already has an answer here:

  • PhantomJS; click an element 11 answers

I run my tests with Karma and PhantomJS:

INFO [karma]: Karma v0.12.32 server started at http://localhost:9876/ INFO [launcher]: Starting browser PhantomJS INFO [PhantomJS 1.9.8 (Windows 7)]: Connected on socket kVOvdbbgtIeUQuV8AAAA wit

In the that test I want to click on the paragraph (p) to get my event-feedback:

// given 
var element = appendToBody("<p id='hello-p'>Hello Hello World!</p>");

element.addEventListener('click', function(event) {
    console.log("1");
});

// when
var p = document.getElementById("hello-p");

console.log(p);
// LOG: <p id="hello-p">Hello Hello World!</p>
console.log(p.id);
// LOG: 'hello-p'

p.click(); // calling click

I end up having this message:

TypeError: 'undefined' is not a function (evaluating 'p.click()')

Q: why p could be undefined?

回答1:

Ok. Bacause PhantomJS based on webkit, I have to create/send event like this:

  var cle = document.createEvent("MouseEvent");
  cle.initEvent("click", true, true);
  var elem = document.getElementById('hello-p');
  elem.dispatchEvent(cle);