在PhantomJS中找不到变量:页面

Lai*_*290 8 javascript phantomjs

我是单元测试和UI测试的初学者

我正在尝试使用以下代码为我的登录页面创建UI测试:

console.log("Teste de Login");

var page = require('webpage').create();
page.open('http://localhost/login', function(status) {
    console.log("Page loadeed");

    if(status === "success") {
        page.render('example1.png');
    }

    page.evaluate(function() {
        // $("#numeroUsuario").val("99734167");
        document.getElementById('numeroUsuario').value = "99734167";
        page.render('exampl2.png');

        // $("#formLogin").submit();
        page.render('example3.png');
    });

    phantom.exit();
});
Run Code Online (Sandbox Code Playgroud)

但是此代码返回以下错误:

> phantomjs.exe ./testLogin.js
Teste de Login
Page loadeed
ReferenceError: Can't find variable: page

  phantomjs://webpage.evaluate():4
  phantomjs://webpage.evaluate():8
Run Code Online (Sandbox Code Playgroud)

元素$("#numeroUsuario")存在的地方.我做错了什么?

Art*_* B. 11

文件说,有关的页面上下文(重点煤矿)以下内容:

执行是沙箱化的,网页无法访问phantom对象,也无法探测自己的设置.

这意味着在page.evaluate()回调函数之外定义的变量不能在其中访问.它还意味着thiswindow对象.

您当然可以将page.evaluate()调用拆分为多个调用,并在Platinum Azure显示page.evaluate()调用之间移动使用外部变量的调用,但如果您想从内部回调内部调用一些PhantomJS函数,则无效.该回调.page.evaluate()

解决方案是使用window.callPhantompage.onCallback.这非常适合异步功能:

var renderId = 0;
page.onCallback = function(data){
    console.log("Callback: " + data.type);
    if (data.type === "exit") {
        phantom.exit();
    } else if (data.type === "render") {
        page.render(data.fname || ("screenshot_" + (renderId++) + ".png"));
    }
};

page.onConsoleMessage = function(msg){
    console.log("remote> " + msg);
};

var getUrl = "http://example.com";
page.open(url, function(){
    page.evaluate(function(getUrl){
        $.get(getUrl, "", function(data){
            console.log(JSON.stringify(data));
            window.callPhantom({ type: "render" });
            window.callPhantom({ type: "exit" });
        });
    }, getUrl);
});
Run Code Online (Sandbox Code Playgroud)

出口可能会干扰先前触发的渲染操作.在这种情况下,肯定可以延迟退出一段固定的时间,例如半秒:

if (data.type === "exit") {
    setTimeout(function(){
        phantom.exit();
    }, 500);
}
Run Code Online (Sandbox Code Playgroud)

此外,无法将page对象传递到页面上下文中,因为只能传入可序列化的对象:

注意:函数的参数和返回值evaluate必须是简单的原始对象.经验法则:如果它可以通过JSON序列化,那么它很好.

闭包功能,DOM节点等,将工作!


Pla*_*ure 3

可以肯定的是,在某个page.evaluate环境中,您无法引用 Phantom 脚本中的任何内容。

在您的情况下,您实际上可以有多个评估调用:

console.log("Teste de Login");

var page = require('webpage').create();
page.open('http://localhost/login', function(status) {
    console.log("Page loadeed");

    if(status === "success") {
        page.render('example1.png');
    }

    page.evaluate(function() {
        // $("#numeroUsuario").val("99734167");
        document.getElementById('numeroUsuario').value = "99734167";
    });

    page.render('exampl2.png');

    page.evaluate(function() {
        // $("#formLogin").submit();
    });

    page.render('example3.png');

    phantom.exit();
});
Run Code Online (Sandbox Code Playgroud)