JS Testing: Trigger jQuery keypress event from CasperJS and PhanthomJS

十年热恋 提交于 2020-01-01 19:42:14

问题


my webpage has a listener to the enter key press event. I am trying to run the casperjs code below to trigger this event, but without success.

Although no error is prompted out, the (evaluate) function returns true and the code works fine from my chrome console, the function result, that should be sending a request to the server is never happening

casper.then(function(){
    var result = this.evaluate(function(term){
        var search_form_id = "#search-form";
        $(search_form_id).val(term);

        jQuery(search_form_id).trigger(jQuery.Event('keypress', {which: 13, keyCode: 13}));

        return true;
    }, 'Techcrunch');
    console.log(result);
});

Is that any issue regarding PhantomJS and jQuery events?


回答1:


It looks like, you can't trigger the keypress event using jQuery. There is a workaround using the underlying casper.page.sendEvent function. Though it is necessary to focus on the element, where the keypress will be triggered. In the following example I use the keepFocus option of the sendKeys function.

var casper = require('casper').create();
casper.start("https://duckduckgo.com/");
casper.then(function() {
    this.sendKeys("#search_form_homepage input[name=q]", "casperjs", { keepFocus: true });
    this.capture("typed.png");
    this.page.sendEvent("keypress", this.page.event.key.Enter);
});

casper.waitForSelector("#links_wrapper");

casper.then(function() {
    this.capture("searched.png");
});

casper.run();


来源:https://stackoverflow.com/questions/23608685/js-testing-trigger-jquery-keypress-event-from-casperjs-and-phanthomjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!