我们想使用 PhantomJS 测试一个 GWT 单页 Web 应用程序。
- 我们加载页面
- 填写登录输入字段
- 点击登录
- 在超时内,查询页面上的元素并打印到控制台
- 10s后退出
问题是第 3 步导致整个主体多次执行,这意味着我们的 page.open() 函数主体中的 console.log 语句会打印多次。
有谁知道问题是什么?我们如何让身体只执行一次?
这是产生这种行为的代码:
var page = require('webpage').create();
page.onConsoleMessage = function (msg) {
console.log(msg);
};
page.open("http://gwt-web-app.com#bookmark", function (status) {
page.evaluate(function () {
console.log('start login');
document.querySelector('input#username').value = 'user';
document.querySelector('input#password').value = 'pass';
document.querySelector('button').click(); // causes body to be executed multiple times
console.log('end login');
});
window.setTimeout(function() {
page.evaluate(function() {
console.log('start element query');
// query elements, and print using console.log
console.log('end element query')
});
}, 4000);
window.setTimeout(function () {
console.log('exit');
phantom.exit();
}, 10000);
});
输出如下(运行后phantomjs test_app.js
):
start login
end login
start login
end login
start login
end login
start login
end login
start login
end login
start login
end login
start login
end login
start login
end login
start login
end login
start login
end login
start login
end login
start element query
end element query
start login
end login
start login
end login
start login
end login
start login
end login
start element query
end element query
start login
end login
start element query
end element query
start login
end login
start element query
end element query
start login
end login
start element query
end element query
start login
end login
start element query
end element query
start login
end login
start element query
end element query
start login
end login
start element query
end element query
start login
end login
start element query
end element query
start element query
end element query
start login
end login
start element query
end element query
start login
end login
start element query
end element query
start login
end login
start element query
end element query
start login
end login
start element query
end element query
start login
end login
start element query
end element query
start login
end login
start element query
end element query
start login
end login
start element query
end element query
start login
end login
exit