PhantomJS/CasperJS AssertExists() is failing

2019-07-03 04:27发布

问题:

I am trying to check wether a selector exists in my webpage but casperjs never finds it.

I've tried two approaches:

1. Without waiting

casper.then(function() {
    // search for 'casperjs' from google form
    this.test.assertExists('#search-form', 'the element exists');
    // this.test.assertExists('.glyphicon.glyphicon-plus', 'the element exists');
});

2. Waiting for selector

casper.waitForSelector('#search-form', function() {
    this.echo("I'm sure #search-form is available in the DOM");
});

3. Another waiting approach

casper.waitFor(function check() {
     return this.evaluate(function() {
         return $('#search-form').length == 1;
     });
 }, function then() {    // step to execute when check() is ok
     test.assertExists('#search-form', 'tabs area is found');
 }, function timeout() { // step to execute if check has failed
     this.echo("Timeout: page did not load in time...").exit();
 });

None of them has been able to find the selector so far. And this selector is loaded from the html, it is not inserted by the javascript.

Any ideas?

回答1:

Well, I think you should check if your selector is in your webpage like that :

casper.then(function(){
    console.log(this.getPageContent());
});

command -pipe the output-: casperjs test yourFile.js > seePageContent.html

Or you might prefer this way (with a wait if needed) :

casper.then(function(){
    this.wait(3000,function(){
        var fs = require('fs');
        fs.write("seePageContent.html", this.getPageContent(), 'w');
    });
});

That way you know if your element is present or not. If not, then your previous step is wrong.