我是测试初学者,无论是单元测试还是 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();
});
但此代码返回以下错误:
> phantomjs.exe ./testLogin.js
Teste de Login
Page loadeed
ReferenceError: Can't find variable: page
phantomjs://webpage.evaluate():4
phantomjs://webpage.evaluate():8
元素 $("#numeroUsuario")
存在的地方。我做错了什么?
最佳答案
documentation说以下关于页面上下文(强调我的):
The execution is sandboxed, the web page has no access to the
phantom
object and it can't probe its own setting.
这意味着在 page.evaluate()
回调函数之外定义的变量在其内部不可访问。这也意味着 this
引用了 window
对象。
您当然可以将 page.evaluate()
调用拆分为多个调用,并将使用外部变量的调用移动到 page.evaluate()
之间像Platinum Azure showed这样的电话, 但如果您想从 page.evaluate()
回调中的回调中调用某些 PhantomJS 函数,则此方法无效。
解决方案是使用 window.callPhantom
and page.onCallback
pair .这非常适合异步函数:
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);
});
退出可能会干扰之前触发的渲染操作。在这种情况下肯定可以将退出延迟一些固定的时间,例如半秒:
if (data.type === "exit") {
setTimeout(function(){
phantom.exit();
}, 500);
}
此外,不可能将 page
对象传递到页面上下文中,因为只能传递可序列化的对象:
Note: The arguments and the return value to the
evaluate
function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.Closures, functions, DOM nodes, etc. will not work!
关于javascript - 找不到变量 : page in PhantomJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32954786/